Launcher.java revision 3d503fbd9468fb2b9fa645f4f7b91e11229edbfa
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.animation.Animator;
21import android.animation.AnimatorListenerAdapter;
22import android.animation.AnimatorSet;
23import android.animation.ObjectAnimator;
24import android.animation.PropertyValuesHolder;
25import android.animation.ValueAnimator;
26import android.app.Activity;
27import android.app.AlertDialog;
28import android.app.Dialog;
29import android.app.SearchManager;
30import android.app.StatusBarManager;
31import android.appwidget.AppWidgetManager;
32import android.appwidget.AppWidgetProviderInfo;
33import android.content.ActivityNotFoundException;
34import android.content.BroadcastReceiver;
35import android.content.ClipData;
36import android.content.ClipDescription;
37import android.content.ComponentName;
38import android.content.ContentResolver;
39import android.content.Context;
40import android.content.DialogInterface;
41import android.content.Intent;
42import android.content.IntentFilter;
43import android.content.Intent.ShortcutIconResource;
44import android.content.pm.ActivityInfo;
45import android.content.pm.PackageManager;
46import android.content.pm.ResolveInfo;
47import android.content.pm.PackageManager.NameNotFoundException;
48import android.content.res.Configuration;
49import android.content.res.Resources;
50import android.content.res.TypedArray;
51import android.database.ContentObserver;
52import android.graphics.Bitmap;
53import android.graphics.Canvas;
54import android.graphics.Rect;
55import android.graphics.drawable.ColorDrawable;
56import android.graphics.drawable.Drawable;
57import android.net.Uri;
58import android.os.AsyncTask;
59import android.os.Bundle;
60import android.os.Environment;
61import android.os.Handler;
62import android.os.Message;
63import android.os.SystemClock;
64import android.os.SystemProperties;
65import android.provider.Settings;
66import android.speech.RecognizerIntent;
67import android.text.Selection;
68import android.text.SpannableStringBuilder;
69import android.text.TextUtils;
70import android.text.method.TextKeyListener;
71import android.util.Log;
72import android.view.Display;
73import android.view.HapticFeedbackConstants;
74import android.view.KeyEvent;
75import android.view.LayoutInflater;
76import android.view.Menu;
77import android.view.MenuItem;
78import android.view.MotionEvent;
79import android.view.Surface;
80import android.view.View;
81import android.view.ViewGroup;
82import android.view.View.OnClickListener;
83import android.view.View.OnLongClickListener;
84import android.view.accessibility.AccessibilityEvent;
85import android.view.animation.DecelerateInterpolator;
86import android.view.inputmethod.InputMethodManager;
87import android.widget.Advanceable;
88import android.widget.EditText;
89import android.widget.ImageView;
90import android.widget.LinearLayout;
91import android.widget.PopupWindow;
92import android.widget.TextView;
93import android.widget.Toast;
94
95import com.android.common.Search;
96import com.android.launcher.R;
97import com.android.launcher2.Workspace.State;
98
99import java.io.DataInputStream;
100import java.io.DataOutputStream;
101import java.io.FileNotFoundException;
102import java.io.IOException;
103import java.util.ArrayList;
104import java.util.HashMap;
105import java.util.List;
106
107/**
108 * Default launcher application.
109 */
110public final class Launcher extends Activity
111        implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
112                   AllAppsView.Watcher, View.OnTouchListener {
113    static final String TAG = "Launcher";
114    static final boolean LOGD = false;
115
116    static final boolean PROFILE_STARTUP = false;
117    static final boolean DEBUG_WIDGETS = false;
118
119    private static final int MENU_GROUP_ADD = 1;
120    private static final int MENU_GROUP_WALLPAPER = MENU_GROUP_ADD + 1;
121
122    private static final int MENU_ADD = Menu.FIRST + 1;
123    private static final int MENU_MANAGE_APPS = MENU_ADD + 1;
124    private static final int MENU_WALLPAPER_SETTINGS = MENU_MANAGE_APPS + 1;
125    private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1;
126    private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1;
127    private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1;
128
129    private static final int REQUEST_CREATE_SHORTCUT = 1;
130    private static final int REQUEST_CREATE_APPWIDGET = 5;
131    private static final int REQUEST_PICK_APPLICATION = 6;
132    private static final int REQUEST_PICK_SHORTCUT = 7;
133    private static final int REQUEST_PICK_APPWIDGET = 9;
134    private static final int REQUEST_PICK_WALLPAPER = 10;
135
136    static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
137
138    static final int SCREEN_COUNT = 5;
139    static final int DEFAULT_SCREEN = 2;
140
141    static final int DIALOG_CREATE_SHORTCUT = 1;
142    static final int DIALOG_RENAME_FOLDER = 2;
143
144    private static final String PREFERENCES = "launcher.preferences";
145
146    // Type: int
147    private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
148    // Type: int
149    private static final String RUNTIME_STATE = "launcher.state";
150    // Type: int
151    private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container";
152    // Type: int
153    private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
154    // Type: int
155    private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x";
156    // Type: int
157    private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y";
158    // Type: boolean
159    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
160    // Type: long
161    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
162
163    private static final String TOOLBAR_ICON_METADATA_NAME = "com.android.launcher.toolbar_icon";
164
165    /** The different states that Launcher can be in. */
166    private enum State { WORKSPACE, APPS_CUSTOMIZE, APPS_CUSTOMIZE_SPRING_LOADED };
167    private State mState = State.WORKSPACE;
168    private AnimatorSet mStateAnimation;
169
170    static final int APPWIDGET_HOST_ID = 1024;
171    private static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300;
172    private static final int EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT = 600;
173
174    private static final Object sLock = new Object();
175    private static int sScreen = DEFAULT_SCREEN;
176
177    private final BroadcastReceiver mCloseSystemDialogsReceiver
178            = new CloseSystemDialogsIntentReceiver();
179    private final ContentObserver mWidgetObserver = new AppWidgetResetObserver();
180
181    private LayoutInflater mInflater;
182
183    private DragController mDragController;
184    private Workspace mWorkspace;
185
186    private AppWidgetManager mAppWidgetManager;
187    private LauncherAppWidgetHost mAppWidgetHost;
188
189    private ItemInfo mPendingAddInfo = new ItemInfo();
190    private int[] mTmpAddItemCellCoordinates = new int[2];
191
192    private FolderInfo mFolderInfo;
193
194    private Hotseat mHotseat;
195    private View mAllAppsButton;
196
197    private SearchDropTargetBar mSearchDeleteBar;
198    private AppsCustomizeTabHost mAppsCustomizeTabHost;
199    private AppsCustomizePagedView mAppsCustomizeContent;
200    private boolean mAutoAdvanceRunning = false;
201
202    private Bundle mSavedState;
203
204    private SpannableStringBuilder mDefaultKeySsb = null;
205
206    private boolean mWorkspaceLoading = true;
207
208    private boolean mPaused = true;
209    private boolean mRestoring;
210    private boolean mWaitingForResult;
211    private boolean mOnResumeNeedsLoad;
212
213    private Bundle mSavedInstanceState;
214
215    private LauncherModel mModel;
216    private IconCache mIconCache;
217    private boolean mUserPresent = true;
218    private boolean mVisible = false;
219    private boolean mAttached = false;
220
221    private static LocaleConfiguration sLocaleConfiguration = null;
222
223    private static HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
224
225    // Hotseats (quick-launch icons next to AllApps)
226    private String[] mHotseatConfig = null;
227    private Intent[] mHotseats = null;
228    private Drawable[] mHotseatIcons = null;
229    private CharSequence[] mHotseatLabels = null;
230
231    private Intent mAppMarketIntent = null;
232
233    // Related to the auto-advancing of widgets
234    private final int ADVANCE_MSG = 1;
235    private final int mAdvanceInterval = 20000;
236    private final int mAdvanceStagger = 250;
237    private long mAutoAdvanceSentTime;
238    private long mAutoAdvanceTimeLeft = -1;
239    private HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance =
240        new HashMap<View, AppWidgetProviderInfo>();
241
242    // Determines how long to wait after a rotation before restoring the screen orientation to
243    // match the sensor state.
244    private final int mRestoreScreenOrientationDelay = 500;
245
246    // External icons saved in case of resource changes, orientation, etc.
247    private static Drawable.ConstantState sGlobalSearchIcon;
248    private static Drawable.ConstantState sVoiceSearchIcon;
249    private static Drawable.ConstantState sAppMarketIcon;
250
251    private DragLayer mDragLayer;
252
253    private BubbleTextView mWaitingForResume;
254
255    private static ArrayList<PendingAddArguments> sPendingAddList
256            = new ArrayList<PendingAddArguments>();
257
258    private static class PendingAddArguments {
259        int requestCode;
260        Intent intent;
261        long container;
262        int screen;
263        int cellX;
264        int cellY;
265    }
266
267    @Override
268    protected void onCreate(Bundle savedInstanceState) {
269        super.onCreate(savedInstanceState);
270        LauncherApplication app = ((LauncherApplication)getApplication());
271        mModel = app.setLauncher(this);
272        mIconCache = app.getIconCache();
273        mDragController = new DragController(this);
274        mInflater = getLayoutInflater();
275
276        mAppWidgetManager = AppWidgetManager.getInstance(this);
277        mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
278        mAppWidgetHost.startListening();
279
280        if (PROFILE_STARTUP) {
281            android.os.Debug.startMethodTracing(
282                    Environment.getExternalStorageDirectory() + "/launcher");
283        }
284
285        loadHotseats();
286        checkForLocaleChange();
287        setContentView(R.layout.launcher);
288        setupViews();
289
290        registerContentObservers();
291
292        lockAllApps();
293
294        mSavedState = savedInstanceState;
295        restoreState(mSavedState);
296
297        // Update customization drawer _after_ restoring the states
298        if (mAppsCustomizeContent != null) {
299            mAppsCustomizeContent.onPackagesUpdated();
300        }
301
302        if (PROFILE_STARTUP) {
303            android.os.Debug.stopMethodTracing();
304        }
305
306        if (!mRestoring) {
307            mModel.startLoader(this, true);
308        }
309
310        // For handling default keys
311        mDefaultKeySsb = new SpannableStringBuilder();
312        Selection.setSelection(mDefaultKeySsb, 0);
313
314        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
315        registerReceiver(mCloseSystemDialogsReceiver, filter);
316
317        // If we have a saved version of these external icons, we load them up immediately
318        if (sGlobalSearchIcon == null || sVoiceSearchIcon == null || sAppMarketIcon == null) {
319            updateIconsAffectedByPackageManagerChanges();
320            updateGlobalSearchIcon();
321        }
322        if (sGlobalSearchIcon != null) {
323             updateGlobalSearchIcon(sGlobalSearchIcon);
324        }
325        if (sVoiceSearchIcon != null) {
326            updateVoiceSearchIcon(sVoiceSearchIcon);
327        }
328        if (sAppMarketIcon != null) {
329            updateAppMarketIcon(sAppMarketIcon);
330        }
331    }
332
333    private void checkForLocaleChange() {
334        if (sLocaleConfiguration == null) {
335            new AsyncTask<Void, Void, LocaleConfiguration>() {
336                @Override
337                protected LocaleConfiguration doInBackground(Void... unused) {
338                    LocaleConfiguration localeConfiguration = new LocaleConfiguration();
339                    readConfiguration(Launcher.this, localeConfiguration);
340                    return localeConfiguration;
341                }
342
343                @Override
344                protected void onPostExecute(LocaleConfiguration result) {
345                    sLocaleConfiguration = result;
346                    checkForLocaleChange();  // recursive, but now with a locale configuration
347                }
348            }.execute();
349            return;
350        }
351
352        final Configuration configuration = getResources().getConfiguration();
353
354        final String previousLocale = sLocaleConfiguration.locale;
355        final String locale = configuration.locale.toString();
356
357        final int previousMcc = sLocaleConfiguration.mcc;
358        final int mcc = configuration.mcc;
359
360        final int previousMnc = sLocaleConfiguration.mnc;
361        final int mnc = configuration.mnc;
362
363        boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
364
365        if (localeChanged) {
366            sLocaleConfiguration.locale = locale;
367            sLocaleConfiguration.mcc = mcc;
368            sLocaleConfiguration.mnc = mnc;
369
370            mIconCache.flush();
371            loadHotseats();
372
373            final LocaleConfiguration localeConfiguration = sLocaleConfiguration;
374            new Thread("WriteLocaleConfiguration") {
375                @Override
376                public void run() {
377                    writeConfiguration(Launcher.this, localeConfiguration);
378                }
379            }.start();
380        }
381    }
382
383    private static class LocaleConfiguration {
384        public String locale;
385        public int mcc = -1;
386        public int mnc = -1;
387    }
388
389    private static void readConfiguration(Context context, LocaleConfiguration configuration) {
390        DataInputStream in = null;
391        try {
392            in = new DataInputStream(context.openFileInput(PREFERENCES));
393            configuration.locale = in.readUTF();
394            configuration.mcc = in.readInt();
395            configuration.mnc = in.readInt();
396        } catch (FileNotFoundException e) {
397            // Ignore
398        } catch (IOException e) {
399            // Ignore
400        } finally {
401            if (in != null) {
402                try {
403                    in.close();
404                } catch (IOException e) {
405                    // Ignore
406                }
407            }
408        }
409    }
410
411    private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
412        DataOutputStream out = null;
413        try {
414            out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
415            out.writeUTF(configuration.locale);
416            out.writeInt(configuration.mcc);
417            out.writeInt(configuration.mnc);
418            out.flush();
419        } catch (FileNotFoundException e) {
420            // Ignore
421        } catch (IOException e) {
422            //noinspection ResultOfMethodCallIgnored
423            context.getFileStreamPath(PREFERENCES).delete();
424        } finally {
425            if (out != null) {
426                try {
427                    out.close();
428                } catch (IOException e) {
429                    // Ignore
430                }
431            }
432        }
433    }
434
435    public DragLayer getDragLayer() {
436        return mDragLayer;
437    }
438
439    static int getScreen() {
440        synchronized (sLock) {
441            return sScreen;
442        }
443    }
444
445    static void setScreen(int screen) {
446        synchronized (sLock) {
447            sScreen = screen;
448        }
449    }
450
451    // Note: This doesn't do all the client-id magic that BrowserProvider does
452    // in Browser. (http://b/2425179)
453    private Uri getDefaultBrowserUri() {
454        String url = getString(R.string.default_browser_url);
455        if (url.indexOf("{CID}") != -1) {
456            url = url.replace("{CID}", "android-google");
457        }
458        return Uri.parse(url);
459    }
460
461    // Load the Intent templates from arrays.xml to populate the hotseats. For
462    // each Intent, if it resolves to a single app, use that as the launch
463    // intent & use that app's label as the contentDescription. Otherwise,
464    // retain the ResolveActivity so the user can pick an app.
465    private void loadHotseats() {
466        if (mHotseatConfig == null) {
467            mHotseatConfig = getResources().getStringArray(R.array.hotseats);
468            if (mHotseatConfig.length > 0) {
469                mHotseats = new Intent[mHotseatConfig.length];
470                mHotseatLabels = new CharSequence[mHotseatConfig.length];
471                mHotseatIcons = new Drawable[mHotseatConfig.length];
472            } else {
473                mHotseats = null;
474                mHotseatIcons = null;
475                mHotseatLabels = null;
476            }
477
478            TypedArray hotseatIconDrawables = getResources().obtainTypedArray(R.array.hotseat_icons);
479            for (int i=0; i<mHotseatConfig.length; i++) {
480                // load icon for this slot; currently unrelated to the actual activity
481                try {
482                    mHotseatIcons[i] = hotseatIconDrawables.getDrawable(i);
483                } catch (ArrayIndexOutOfBoundsException ex) {
484                    Log.w(TAG, "Missing hotseat_icons array item #" + i);
485                    mHotseatIcons[i] = null;
486                }
487            }
488            hotseatIconDrawables.recycle();
489        }
490
491        PackageManager pm = getPackageManager();
492        for (int i=0; i<mHotseatConfig.length; i++) {
493            Intent intent = null;
494            if (mHotseatConfig[i].equals("*BROWSER*")) {
495                // magic value meaning "launch user's default web browser"
496                // replace it with a generic web request so we can see if there is indeed a default
497                String defaultUri = getString(R.string.default_browser_url);
498                intent = new Intent(
499                        Intent.ACTION_VIEW,
500                        ((defaultUri != null)
501                            ? Uri.parse(defaultUri)
502                            : getDefaultBrowserUri())
503                    ).addCategory(Intent.CATEGORY_BROWSABLE);
504                // note: if the user launches this without a default set, she
505                // will always be taken to the default URL above; this is
506                // unavoidable as we must specify a valid URL in order for the
507                // chooser to appear, and once the user selects something, that
508                // URL is unavoidably sent to the chosen app.
509            } else {
510                try {
511                    intent = Intent.parseUri(mHotseatConfig[i], 0);
512                } catch (java.net.URISyntaxException ex) {
513                    Log.w(TAG, "Invalid hotseat intent: " + mHotseatConfig[i]);
514                    // bogus; leave intent=null
515                }
516            }
517
518            if (intent == null) {
519                mHotseats[i] = null;
520                mHotseatLabels[i] = getText(R.string.activity_not_found);
521                continue;
522            }
523
524            if (LOGD) {
525                Log.d(TAG, "loadHotseats: hotseat " + i
526                    + " initial intent=["
527                    + intent.toUri(Intent.URI_INTENT_SCHEME)
528                    + "]");
529            }
530
531            ResolveInfo bestMatch = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
532            List<ResolveInfo> allMatches = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
533            if (LOGD) {
534                Log.d(TAG, "Best match for intent: " + bestMatch);
535                Log.d(TAG, "All matches: ");
536                for (ResolveInfo ri : allMatches) {
537                    Log.d(TAG, "  --> " + ri);
538                }
539            }
540            // did this resolve to a single app, or the resolver?
541            if (allMatches.size() == 0 || bestMatch == null) {
542                // can't find any activity to handle this. let's leave the
543                // intent as-is and let Launcher show a toast when it fails
544                // to launch.
545                mHotseats[i] = intent;
546
547                // set accessibility text to "Not installed"
548                mHotseatLabels[i] = getText(R.string.activity_not_found);
549            } else {
550                boolean found = false;
551                for (ResolveInfo ri : allMatches) {
552                    if (bestMatch.activityInfo.name.equals(ri.activityInfo.name)
553                        && bestMatch.activityInfo.applicationInfo.packageName
554                            .equals(ri.activityInfo.applicationInfo.packageName)) {
555                        found = true;
556                        break;
557                    }
558                }
559
560                if (!found) {
561                    if (LOGD) Log.d(TAG, "Multiple options, no default yet");
562                    // the bestMatch is probably the ResolveActivity, meaning the
563                    // user has not yet selected a default
564                    // so: we'll keep the original intent for now
565                    mHotseats[i] = intent;
566
567                    // set the accessibility text to "Select shortcut"
568                    mHotseatLabels[i] = getText(R.string.title_select_shortcut);
569                } else {
570                    // we have an app!
571                    // now reconstruct the intent to launch it through the front
572                    // door
573                    ComponentName com = new ComponentName(
574                        bestMatch.activityInfo.applicationInfo.packageName,
575                        bestMatch.activityInfo.name);
576                    mHotseats[i] = new Intent(Intent.ACTION_MAIN).setComponent(com);
577
578                    // load the app label for accessibility
579                    mHotseatLabels[i] = bestMatch.activityInfo.loadLabel(pm);
580                }
581            }
582
583            if (LOGD) {
584                Log.d(TAG, "loadHotseats: hotseat " + i
585                    + " final intent=["
586                    + ((mHotseats[i] == null)
587                        ? "null"
588                        : mHotseats[i].toUri(Intent.URI_INTENT_SCHEME))
589                    + "] label=[" + mHotseatLabels[i]
590                    + "]"
591                    );
592            }
593        }
594    }
595
596    /**
597     * Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have
598     * a configuration step, this allows the proper animations to run after other transitions.
599     */
600    private boolean completeAdd(PendingAddArguments args) {
601        switch (args.requestCode) {
602            case REQUEST_PICK_APPLICATION:
603                completeAddApplication(args.intent, args.container, args.screen, args.cellX,
604                        args.cellY);
605                break;
606            case REQUEST_PICK_SHORTCUT:
607                processShortcut(args.intent);
608                break;
609            case REQUEST_CREATE_SHORTCUT:
610                completeAddShortcut(args.intent, args.container, args.screen, args.cellX,
611                        args.cellY);
612                return true;
613            case REQUEST_PICK_APPWIDGET:
614                addAppWidgetFromPick(args.intent);
615                break;
616            case REQUEST_CREATE_APPWIDGET:
617                int appWidgetId = args.intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
618                completeAddAppWidget(appWidgetId, args.container, args.screen);
619                return true;
620            case REQUEST_PICK_WALLPAPER:
621                // We just wanted the activity result here so we can clear mWaitingForResult
622                break;
623        }
624        return false;
625    }
626
627    @Override
628    protected void onActivityResult(final int requestCode, int resultCode, final Intent data) {
629        boolean delayExitSpringLoadedMode = false;
630        mWaitingForResult = false;
631
632        // The pattern used here is that a user PICKs a specific application,
633        // which, depending on the target, might need to CREATE the actual target.
634
635        // For example, the user would PICK_SHORTCUT for "Music playlist", and we
636        // launch over to the Music app to actually CREATE_SHORTCUT.
637        if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID  &&
638                mPendingAddInfo.screen > -1) {
639            final PendingAddArguments args = new PendingAddArguments();
640            args.requestCode = requestCode;
641            args.intent = data;
642            args.container = mPendingAddInfo.container;
643            args.screen = mPendingAddInfo.screen;
644            args.cellX = mPendingAddInfo.cellX;
645            args.cellY = mPendingAddInfo.cellY;
646
647            // If the loader is still running, defer the add until it is done.
648            if (isWorkspaceLocked()) {
649                sPendingAddList.add(args);
650            } else {
651                delayExitSpringLoadedMode = completeAdd(args);
652            }
653        } else if ((requestCode == REQUEST_PICK_APPWIDGET ||
654                requestCode == REQUEST_CREATE_APPWIDGET) && resultCode == RESULT_CANCELED) {
655            if (data != null) {
656                // Clean up the appWidgetId if we canceled
657                int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
658                if (appWidgetId != -1) {
659                    mAppWidgetHost.deleteAppWidgetId(appWidgetId);
660                }
661            }
662        }
663
664        // Exit spring loaded mode if necessary after cancelling the configuration of a widget
665        exitSpringLoadedDragModeDelayed(delayExitSpringLoadedMode);
666    }
667
668    @Override
669    protected void onResume() {
670        super.onResume();
671        mPaused = false;
672        if (mRestoring || mOnResumeNeedsLoad) {
673            mWorkspaceLoading = true;
674            mModel.startLoader(this, true);
675            mRestoring = false;
676            mOnResumeNeedsLoad = false;
677        }
678        if (mWaitingForResume != null) {
679            mWaitingForResume.setStayPressed(false);
680        }
681        // When we resume Launcher, a different Activity might be responsible for the app
682        // market intent, so refresh the icon
683        updateAppMarketIcon();
684    }
685
686    @Override
687    protected void onPause() {
688        super.onPause();
689        mPaused = true;
690        mDragController.cancelDrag();
691    }
692
693    @Override
694    public Object onRetainNonConfigurationInstance() {
695        // Flag the loader to stop early before switching
696        mModel.stopLoader();
697        if (mAppsCustomizeContent != null) {
698            mAppsCustomizeContent.surrender();
699        }
700        return Boolean.TRUE;
701    }
702
703    // We can't hide the IME if it was forced open.  So don't bother
704    /*
705    @Override
706    public void onWindowFocusChanged(boolean hasFocus) {
707        super.onWindowFocusChanged(hasFocus);
708
709        if (hasFocus) {
710            final InputMethodManager inputManager = (InputMethodManager)
711                    getSystemService(Context.INPUT_METHOD_SERVICE);
712            WindowManager.LayoutParams lp = getWindow().getAttributes();
713            inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new
714                        android.os.Handler()) {
715                        protected void onReceiveResult(int resultCode, Bundle resultData) {
716                            Log.d(TAG, "ResultReceiver got resultCode=" + resultCode);
717                        }
718                    });
719            Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged");
720        }
721    }
722    */
723
724    private boolean acceptFilter() {
725        final InputMethodManager inputManager = (InputMethodManager)
726                getSystemService(Context.INPUT_METHOD_SERVICE);
727        return !inputManager.isFullscreenMode();
728    }
729
730    @Override
731    public boolean onKeyDown(int keyCode, KeyEvent event) {
732        final int uniChar = event.getUnicodeChar();
733        final boolean handled = super.onKeyDown(keyCode, event);
734        final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar);
735        if (!handled && acceptFilter() && isKeyNotWhitespace) {
736            boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
737                    keyCode, event);
738            if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
739                // something usable has been typed - start a search
740                // the typed text will be retrieved and cleared by
741                // showSearchDialog()
742                // If there are multiple keystrokes before the search dialog takes focus,
743                // onSearchRequested() will be called for every keystroke,
744                // but it is idempotent, so it's fine.
745                return onSearchRequested();
746            }
747        }
748
749        // Eat the long press event so the keyboard doesn't come up.
750        if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
751            return true;
752        }
753
754        return handled;
755    }
756
757    private String getTypedText() {
758        return mDefaultKeySsb.toString();
759    }
760
761    private void clearTypedText() {
762        mDefaultKeySsb.clear();
763        mDefaultKeySsb.clearSpans();
764        Selection.setSelection(mDefaultKeySsb, 0);
765    }
766
767    /**
768     * Given the integer (ordinal) value of a State enum instance, convert it to a variable of type
769     * State
770     */
771    private static State intToState(int stateOrdinal) {
772        State state = State.WORKSPACE;
773        final State[] stateValues = State.values();
774        for (int i = 0; i < stateValues.length; i++) {
775            if (stateValues[i].ordinal() == stateOrdinal) {
776                state = stateValues[i];
777                break;
778            }
779        }
780        return state;
781    }
782
783    /**
784     * Restores the previous state, if it exists.
785     *
786     * @param savedState The previous state.
787     */
788    private void restoreState(Bundle savedState) {
789        if (savedState == null) {
790            return;
791        }
792
793        State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
794
795        if (state == State.APPS_CUSTOMIZE) {
796            showAllApps(false);
797        }
798
799        final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
800        if (currentScreen > -1) {
801            mWorkspace.setCurrentPage(currentScreen);
802        }
803
804        final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
805        final int pendingAddScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
806
807
808        if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
809            mPendingAddInfo.container = pendingAddContainer;
810            mPendingAddInfo.screen = pendingAddScreen;
811            mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
812            mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
813            mRestoring = true;
814        }
815
816        boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
817        if (renameFolder) {
818            long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
819            mFolderInfo = mModel.getFolderById(this, sFolders, id);
820            mRestoring = true;
821        }
822
823
824        // Restore the AppsCustomize tab
825        if (mAppsCustomizeTabHost != null) {
826            String curTab = savedState.getString("apps_customize_currentTab");
827            if (curTab != null) {
828                // We set this directly so that there is no delay before the tab is set
829                mAppsCustomizeContent.setContentType(
830                        mAppsCustomizeTabHost.getContentTypeForTabTag(curTab));
831                mAppsCustomizeTabHost.setCurrentTabByTag(curTab);
832            }
833
834            // Note: currently we do not restore the page for the AppsCustomize pane because the
835            // change in layout can drastically affect the saved page index
836        }
837    }
838
839    /**
840     * Finds all the views we need and configure them properly.
841     */
842    private void setupViews() {
843        final DragController dragController = mDragController;
844
845        mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
846        mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
847
848        // Setup the drag layer
849        mDragLayer.setup(this, dragController);
850
851        // Setup the hotseat
852        mHotseat = (Hotseat) findViewById(R.id.hotseat);
853        if (mHotseat != null) {
854            mHotseat.setup(this);
855        }
856
857        // Setup the workspace
858        mWorkspace.setHapticFeedbackEnabled(false);
859        mWorkspace.setOnLongClickListener(this);
860        mWorkspace.setup(this, dragController);
861        dragController.addDragListener(mWorkspace);
862
863        // Get the search/delete bar
864        mSearchDeleteBar = (SearchDropTargetBar) mDragLayer.findViewById(R.id.qsb_bar);
865
866        // Setup AppsCustomize
867        mAppsCustomizeTabHost = (AppsCustomizeTabHost)
868                findViewById(R.id.apps_customize_pane);
869        mAppsCustomizeContent = (AppsCustomizePagedView)
870                mAppsCustomizeTabHost.findViewById(R.id.apps_customize_pane_content);
871        mAppsCustomizeContent.setup(this, dragController);
872
873
874
875        // Setup the drag controller (drop targets have to be added in reverse order in priority)
876        dragController.setDragScoller(mWorkspace);
877        dragController.setScrollView(mDragLayer);
878        dragController.setMoveTarget(mWorkspace);
879        dragController.addDropTarget(mWorkspace);
880        if (mSearchDeleteBar != null) {
881            mSearchDeleteBar.setup(this, dragController);
882        }
883    }
884
885
886
887    /**
888     * Creates a view representing a shortcut.
889     *
890     * @param info The data structure describing the shortcut.
891     *
892     * @return A View inflated from R.layout.application.
893     */
894    View createShortcut(ShortcutInfo info) {
895        return createShortcut(R.layout.application,
896                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info);
897    }
898
899    /**
900     * Creates a view representing a shortcut inflated from the specified resource.
901     *
902     * @param layoutResId The id of the XML layout used to create the shortcut.
903     * @param parent The group the shortcut belongs to.
904     * @param info The data structure describing the shortcut.
905     *
906     * @return A View inflated from layoutResId.
907     */
908    View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) {
909        BubbleTextView favorite = (BubbleTextView) mInflater.inflate(layoutResId, parent, false);
910        favorite.applyFromShortcutInfo(info, mIconCache);
911        favorite.setOnClickListener(this);
912        return favorite;
913    }
914
915    /**
916     * Add an application shortcut to the workspace.
917     *
918     * @param data The intent describing the application.
919     * @param cellInfo The position on screen where to create the shortcut.
920     */
921    void completeAddApplication(Intent data, long container, int screen, int cellX, int cellY) {
922        final int[] cellXY = mTmpAddItemCellCoordinates;
923        final CellLayout layout = getCellLayout(container, screen);
924
925        // First we check if we already know the exact location where we want to add this item.
926        if (cellX >= 0 && cellY >= 0) {
927            cellXY[0] = cellX;
928            cellXY[1] = cellY;
929        } else if (!layout.findCellForSpan(cellXY, 1, 1)) {
930            showOutOfSpaceMessage();
931            return;
932        }
933
934        final ShortcutInfo info = mModel.getShortcutInfo(getPackageManager(), data, this);
935
936        if (info != null) {
937            info.setActivity(data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK |
938                    Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
939            info.container = ItemInfo.NO_ID;
940            mWorkspace.addApplicationShortcut(info, layout, container, screen, cellXY[0], cellXY[1],
941                    isWorkspaceLocked(), cellX, cellY);
942        } else {
943            Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data);
944        }
945    }
946
947    /**
948     * Add a shortcut to the workspace.
949     *
950     * @param data The intent describing the shortcut.
951     * @param cellInfo The position on screen where to create the shortcut.
952     */
953    private void completeAddShortcut(Intent data, long container, int screen, int cellX,
954            int cellY) {
955        int[] cellXY = mTmpAddItemCellCoordinates;
956        int[] touchXY = mPendingAddInfo.dropPos;
957        CellLayout layout = getCellLayout(container, screen);
958
959        boolean foundCellSpan = false;
960
961        // First we check if we already know the exact location where we want to add this item.
962        if (cellX >= 0 && cellY >= 0) {
963            cellXY[0] = cellX;
964            cellXY[1] = cellY;
965            foundCellSpan = true;
966        } else if (touchXY != null) {
967            // when dragging and dropping, just find the closest free spot
968            int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY);
969            foundCellSpan = (result != null);
970        } else {
971            foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
972        }
973
974        if (!foundCellSpan) {
975            showOutOfSpaceMessage();
976            return;
977        }
978
979        final ShortcutInfo info = mModel.addShortcut(
980                this, data, container, screen, cellXY[0], cellXY[1], false);
981
982        if (!mRestoring) {
983            final View view = createShortcut(info);
984            mWorkspace.addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1,
985                    isWorkspaceLocked());
986        }
987    }
988
989    /**
990     * Add a widget to the workspace.
991     *
992     * @param appWidgetId The app widget id
993     * @param cellInfo The position on screen where to create the widget.
994     */
995    private void completeAddAppWidget(final int appWidgetId, long container, int screen) {
996        AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
997
998        // Calculate the grid spans needed to fit this widget
999        CellLayout layout = getCellLayout(container, screen);
1000
1001        // We want to account for the extra amount of padding that we are adding to the widget
1002        // to ensure that it gets the full amount of space that it has requested
1003        Resources r = getResources();
1004        int requiredWidth = appWidgetInfo.minWidth +
1005                r.getDimensionPixelSize(R.dimen.app_widget_padding_left) +
1006                r.getDimensionPixelSize(R.dimen.app_widget_padding_right);
1007        int requiredHeight = appWidgetInfo.minHeight +
1008                r.getDimensionPixelSize(R.dimen.app_widget_padding_top) +
1009                r.getDimensionPixelSize(R.dimen.app_widget_padding_bottom);
1010        int[] spanXY = layout.rectToCell(requiredWidth, requiredHeight, null);
1011
1012        // Try finding open space on Launcher screen
1013        // We have saved the position to which the widget was dragged-- this really only matters
1014        // if we are placing widgets on a "spring-loaded" screen
1015        int[] cellXY = mTmpAddItemCellCoordinates;
1016        int[] touchXY = mPendingAddInfo.dropPos;
1017        boolean foundCellSpan = false;
1018        if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) {
1019            cellXY[0] = mPendingAddInfo.cellX;
1020            cellXY[1] = mPendingAddInfo.cellY;
1021            foundCellSpan = true;
1022        } else if (touchXY != null) {
1023            // when dragging and dropping, just find the closest free spot
1024            int[] result = layout.findNearestVacantArea(
1025                    touchXY[0], touchXY[1], spanXY[0], spanXY[1], cellXY);
1026            foundCellSpan = (result != null);
1027        } else {
1028            foundCellSpan = layout.findCellForSpan(cellXY, spanXY[0], spanXY[1]);
1029        }
1030
1031        if (!foundCellSpan) {
1032            if (appWidgetId != -1) {
1033                // Deleting an app widget ID is a void call but writes to disk before returning
1034                // to the caller...
1035                new Thread("deleteAppWidgetId") {
1036                    public void run() {
1037                        mAppWidgetHost.deleteAppWidgetId(appWidgetId);
1038                    }
1039                }.start();
1040            }
1041            showOutOfSpaceMessage();
1042            return;
1043        }
1044
1045        // Build Launcher-specific widget info and save to database
1046        LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
1047        launcherInfo.spanX = spanXY[0];
1048        launcherInfo.spanY = spanXY[1];
1049
1050        LauncherModel.addItemToDatabase(this, launcherInfo,
1051                container, screen, cellXY[0], cellXY[1], false);
1052
1053        if (!mRestoring) {
1054            // Perform actual inflation because we're live
1055            launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
1056
1057            launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
1058            launcherInfo.hostView.setTag(launcherInfo);
1059
1060            mWorkspace.addInScreen(launcherInfo.hostView, container, screen, cellXY[0], cellXY[1],
1061                    launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
1062
1063            addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
1064        }
1065    }
1066
1067    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1068        @Override
1069        public void onReceive(Context context, Intent intent) {
1070            final String action = intent.getAction();
1071            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
1072                mUserPresent = false;
1073                mDragLayer.clearAllResizeFrames();
1074                updateRunning();
1075
1076                // Reset AllApps to it's initial state
1077                if (mAppsCustomizeContent != null) {
1078                    mAppsCustomizeContent.reset();
1079                }
1080            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
1081                mUserPresent = true;
1082                updateRunning();
1083            }
1084        }
1085    };
1086
1087    @Override
1088    public void onAttachedToWindow() {
1089        super.onAttachedToWindow();
1090
1091        // Listen for broadcasts related to user-presence
1092        final IntentFilter filter = new IntentFilter();
1093        filter.addAction(Intent.ACTION_SCREEN_OFF);
1094        filter.addAction(Intent.ACTION_USER_PRESENT);
1095        registerReceiver(mReceiver, filter);
1096
1097        mAttached = true;
1098        mVisible = true;
1099    }
1100
1101    @Override
1102    public void onDetachedFromWindow() {
1103        super.onDetachedFromWindow();
1104        mVisible = false;
1105        mDragLayer.clearAllResizeFrames();
1106
1107        if (mAttached) {
1108            unregisterReceiver(mReceiver);
1109            mAttached = false;
1110        }
1111        updateRunning();
1112    }
1113
1114    public void onWindowVisibilityChanged(int visibility) {
1115        mVisible = visibility == View.VISIBLE;
1116        updateRunning();
1117    }
1118
1119    private void sendAdvanceMessage(long delay) {
1120        mHandler.removeMessages(ADVANCE_MSG);
1121        Message msg = mHandler.obtainMessage(ADVANCE_MSG);
1122        mHandler.sendMessageDelayed(msg, delay);
1123        mAutoAdvanceSentTime = System.currentTimeMillis();
1124    }
1125
1126    private void updateRunning() {
1127        boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
1128        if (autoAdvanceRunning != mAutoAdvanceRunning) {
1129            mAutoAdvanceRunning = autoAdvanceRunning;
1130            if (autoAdvanceRunning) {
1131                long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
1132                sendAdvanceMessage(delay);
1133            } else {
1134                if (!mWidgetsToAdvance.isEmpty()) {
1135                    mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
1136                            (System.currentTimeMillis() - mAutoAdvanceSentTime));
1137                }
1138                mHandler.removeMessages(ADVANCE_MSG);
1139                mHandler.removeMessages(0); // Remove messages sent using postDelayed()
1140            }
1141        }
1142    }
1143
1144    private final Handler mHandler = new Handler() {
1145        @Override
1146        public void handleMessage(Message msg) {
1147            if (msg.what == ADVANCE_MSG) {
1148                int i = 0;
1149                for (View key: mWidgetsToAdvance.keySet()) {
1150                    final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
1151                    final int delay = mAdvanceStagger * i;
1152                    if (v instanceof Advanceable) {
1153                       postDelayed(new Runnable() {
1154                           public void run() {
1155                               ((Advanceable) v).advance();
1156                           }
1157                       }, delay);
1158                    }
1159                    i++;
1160                }
1161                sendAdvanceMessage(mAdvanceInterval);
1162            }
1163        }
1164    };
1165
1166    void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
1167        if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
1168        View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
1169        if (v instanceof Advanceable) {
1170            mWidgetsToAdvance.put(hostView, appWidgetInfo);
1171            ((Advanceable) v).fyiWillBeAdvancedByHostKThx();
1172            updateRunning();
1173        }
1174    }
1175
1176    void removeWidgetToAutoAdvance(View hostView) {
1177        if (mWidgetsToAdvance.containsKey(hostView)) {
1178            mWidgetsToAdvance.remove(hostView);
1179            updateRunning();
1180        }
1181    }
1182
1183    public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
1184        removeWidgetToAutoAdvance(launcherInfo.hostView);
1185        launcherInfo.hostView = null;
1186    }
1187
1188    void showOutOfSpaceMessage() {
1189        Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1190    }
1191
1192    public LauncherAppWidgetHost getAppWidgetHost() {
1193        return mAppWidgetHost;
1194    }
1195
1196    public LauncherModel getModel() {
1197        return mModel;
1198    }
1199
1200    void closeSystemDialogs() {
1201        getWindow().closeAllPanels();
1202
1203        try {
1204            dismissDialog(DIALOG_CREATE_SHORTCUT);
1205            // Unlock the workspace if the dialog was showing
1206        } catch (Exception e) {
1207            // An exception is thrown if the dialog is not visible, which is fine
1208        }
1209
1210        try {
1211            dismissDialog(DIALOG_RENAME_FOLDER);
1212            // Unlock the workspace if the dialog was showing
1213        } catch (Exception e) {
1214            // An exception is thrown if the dialog is not visible, which is fine
1215        }
1216
1217        // Whatever we were doing is hereby canceled.
1218        mWaitingForResult = false;
1219    }
1220
1221    @Override
1222    protected void onNewIntent(Intent intent) {
1223        super.onNewIntent(intent);
1224
1225        // Close the menu
1226        if (Intent.ACTION_MAIN.equals(intent.getAction())) {
1227            // also will cancel mWaitingForResult.
1228            closeSystemDialogs();
1229
1230            closeFolder();
1231
1232            boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
1233                        != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
1234
1235            // In all these cases, only animate if we're already on home
1236            mWorkspace.unshrink(alreadyOnHome);
1237            mWorkspace.exitWidgetResizeMode();
1238            if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive()) {
1239                mWorkspace.moveToDefaultScreen(true);
1240            }
1241            showWorkspace(alreadyOnHome);
1242
1243            final View v = getWindow().peekDecorView();
1244            if (v != null && v.getWindowToken() != null) {
1245                InputMethodManager imm = (InputMethodManager)getSystemService(
1246                        INPUT_METHOD_SERVICE);
1247                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
1248            }
1249
1250            // Reset AllApps to its initial state
1251            if (mAppsCustomizeContent != null) {
1252                mAppsCustomizeContent.reset();
1253            }
1254        }
1255    }
1256
1257    @Override
1258    protected void onRestoreInstanceState(Bundle savedInstanceState) {
1259        // Do not call super here
1260        mSavedInstanceState = savedInstanceState;
1261    }
1262
1263    @Override
1264    protected void onSaveInstanceState(Bundle outState) {
1265        outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentPage());
1266        super.onSaveInstanceState(outState);
1267
1268        outState.putInt(RUNTIME_STATE, mState.ordinal());
1269        // We close any open folder since it will not be re-opened, and we need to make sure
1270        // this state is reflected.
1271        closeFolder();
1272
1273        if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screen > -1 &&
1274                mWaitingForResult) {
1275            outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
1276            outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screen);
1277            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
1278            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
1279        }
1280
1281        if (mFolderInfo != null && mWaitingForResult) {
1282            outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
1283            outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
1284        }
1285
1286        // Save the current AppsCustomize tab
1287        if (mAppsCustomizeTabHost != null) {
1288            String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag();
1289            if (currentTabTag != null) {
1290                outState.putString("apps_customize_currentTab", currentTabTag);
1291            }
1292        }
1293    }
1294
1295    @Override
1296    public void onDestroy() {
1297        super.onDestroy();
1298
1299        // Stop callbacks from LauncherModel
1300        LauncherApplication app = ((LauncherApplication) getApplication());
1301        mModel.stopLoader();
1302        app.setLauncher(null);
1303
1304        try {
1305            mAppWidgetHost.stopListening();
1306        } catch (NullPointerException ex) {
1307            Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
1308        }
1309        mAppWidgetHost = null;
1310
1311        mWidgetsToAdvance.clear();
1312
1313        TextKeyListener.getInstance().release();
1314
1315
1316        unbindWorkspaceAndHotseatItems();
1317
1318        getContentResolver().unregisterContentObserver(mWidgetObserver);
1319        unregisterReceiver(mCloseSystemDialogsReceiver);
1320
1321        ((ViewGroup) mWorkspace.getParent()).removeAllViews();
1322        mWorkspace.removeAllViews();
1323        mWorkspace = null;
1324        mDragController = null;
1325
1326        ValueAnimator.clearAllAnimations();
1327    }
1328
1329    public DragController getDragController() {
1330        return mDragController;
1331    }
1332
1333    @Override
1334    public void startActivityForResult(Intent intent, int requestCode) {
1335        if (requestCode >= 0) mWaitingForResult = true;
1336        super.startActivityForResult(intent, requestCode);
1337    }
1338
1339    @Override
1340    public void startSearch(String initialQuery, boolean selectInitialQuery,
1341            Bundle appSearchData, boolean globalSearch) {
1342
1343        showWorkspace(true);
1344
1345        if (initialQuery == null) {
1346            // Use any text typed in the launcher as the initial query
1347            initialQuery = getTypedText();
1348            clearTypedText();
1349        }
1350        if (appSearchData == null) {
1351            appSearchData = new Bundle();
1352            appSearchData.putString(Search.SOURCE, "launcher-search");
1353        }
1354
1355        final SearchManager searchManager =
1356                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
1357        searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
1358            appSearchData, globalSearch);
1359    }
1360
1361    @Override
1362    public boolean onCreateOptionsMenu(Menu menu) {
1363        if (isWorkspaceLocked()) {
1364            return false;
1365        }
1366
1367        super.onCreateOptionsMenu(menu);
1368
1369        menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
1370                .setIcon(android.R.drawable.ic_menu_add)
1371                .setAlphabeticShortcut('A');
1372        menu.add(0, MENU_MANAGE_APPS, 0, R.string.menu_manage_apps)
1373                .setIcon(android.R.drawable.ic_menu_manage)
1374                .setAlphabeticShortcut('M');
1375        menu.add(MENU_GROUP_WALLPAPER, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
1376                 .setIcon(android.R.drawable.ic_menu_gallery)
1377                 .setAlphabeticShortcut('W');
1378        menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
1379                .setIcon(android.R.drawable.ic_search_category_default)
1380                .setAlphabeticShortcut(SearchManager.MENU_KEY);
1381        menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
1382                .setIcon(com.android.internal.R.drawable.ic_menu_notifications)
1383                .setAlphabeticShortcut('N');
1384
1385        final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
1386        settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1387                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1388
1389        menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
1390                .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
1391                .setIntent(settings);
1392
1393        return true;
1394    }
1395
1396    @Override
1397    public boolean onPrepareOptionsMenu(Menu menu) {
1398        super.onPrepareOptionsMenu(menu);
1399
1400        // TODO-APPS_CUSTOMIZE: Remove this for the phone UI at some point, along with all the menu
1401        // related code?
1402        if (mAppsCustomizeContent != null && mAppsCustomizeContent.isAnimating()) return false;
1403
1404        return true;
1405    }
1406
1407    @Override
1408    public boolean onOptionsItemSelected(MenuItem item) {
1409        switch (item.getItemId()) {
1410            case MENU_ADD:
1411                addItems();
1412                return true;
1413            case MENU_MANAGE_APPS:
1414                manageApps();
1415                return true;
1416            case MENU_WALLPAPER_SETTINGS:
1417                startWallpaper();
1418                return true;
1419            case MENU_SEARCH:
1420                onSearchRequested();
1421                return true;
1422            case MENU_NOTIFICATIONS:
1423                showNotifications();
1424                return true;
1425        }
1426
1427        return super.onOptionsItemSelected(item);
1428    }
1429
1430    /**
1431     * Indicates that we want global search for this activity by setting the globalSearch
1432     * argument for {@link #startSearch} to true.
1433     */
1434
1435    @Override
1436    public boolean onSearchRequested() {
1437        startSearch(null, false, null, true);
1438        return true;
1439    }
1440
1441    public boolean isWorkspaceLocked() {
1442        return mWorkspaceLoading || mWaitingForResult;
1443    }
1444
1445    private void addItems() {
1446        showWorkspace(true);
1447        showAddDialog();
1448    }
1449
1450    private void resetAddInfo() {
1451        mPendingAddInfo.container = ItemInfo.NO_ID;
1452        mPendingAddInfo.screen = -1;
1453        mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1;
1454        mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1;
1455        mPendingAddInfo.dropPos = null;
1456    }
1457
1458    private void manageApps() {
1459        startActivity(new Intent(android.provider.Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS));
1460    }
1461
1462    void addAppWidgetFromPick(Intent data) {
1463        // TODO: catch bad widget exception when sent
1464        int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
1465        // TODO: Is this log message meaningful?
1466        if (LOGD) Log.d(TAG, "dumping extras content=" + data.getExtras());
1467        addAppWidgetImpl(appWidgetId, null);
1468    }
1469
1470    void addAppWidgetImpl(int appWidgetId, PendingAddWidgetInfo info) {
1471        AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1472
1473        if (appWidget.configure != null) {
1474            // Launch over to configure widget, if needed
1475            Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
1476            intent.setComponent(appWidget.configure);
1477            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1478            if (info != null) {
1479                if (info.mimeType != null && !info.mimeType.isEmpty()) {
1480                    intent.putExtra(
1481                            InstallWidgetReceiver.EXTRA_APPWIDGET_CONFIGURATION_DATA_MIME_TYPE,
1482                            info.mimeType);
1483
1484                    final String mimeType = info.mimeType;
1485                    final ClipData clipData = (ClipData) info.configurationData;
1486                    final ClipDescription clipDesc = clipData.getDescription();
1487                    for (int i = 0; i < clipDesc.getMimeTypeCount(); ++i) {
1488                        if (clipDesc.getMimeType(i).equals(mimeType)) {
1489                            final ClipData.Item item = clipData.getItemAt(i);
1490                            final CharSequence stringData = item.getText();
1491                            final Uri uriData = item.getUri();
1492                            final Intent intentData = item.getIntent();
1493                            final String key =
1494                                InstallWidgetReceiver.EXTRA_APPWIDGET_CONFIGURATION_DATA;
1495                            if (uriData != null) {
1496                                intent.putExtra(key, uriData);
1497                            } else if (intentData != null) {
1498                                intent.putExtra(key, intentData);
1499                            } else if (stringData != null) {
1500                                intent.putExtra(key, stringData);
1501                            }
1502                            break;
1503                        }
1504                    }
1505                }
1506            }
1507
1508            startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET);
1509        } else {
1510            // Otherwise just add it
1511            completeAddAppWidget(appWidgetId, info.container, info.screen);
1512
1513            // Exit spring loaded mode if necessary after adding the widget
1514            exitSpringLoadedDragModeDelayed(false);
1515        }
1516    }
1517
1518    /**
1519     * Process a shortcut drop.
1520     *
1521     * @param componentName The name of the component
1522     * @param screen The screen where it should be added
1523     * @param cell The cell it should be added to, optional
1524     * @param position The location on the screen where it was dropped, optional
1525     */
1526    void processShortcutFromDrop(ComponentName componentName, long container, int screen,
1527            int[] cell, int[] loc) {
1528        resetAddInfo();
1529        mPendingAddInfo.container = container;
1530        mPendingAddInfo.screen = screen;
1531        mPendingAddInfo.dropPos = loc;
1532
1533        if (cell != null) {
1534            mPendingAddInfo.cellX = cell[0];
1535            mPendingAddInfo.cellY = cell[1];
1536        }
1537
1538        Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
1539        createShortcutIntent.setComponent(componentName);
1540        processShortcut(createShortcutIntent);
1541    }
1542
1543    /**
1544     * Process a widget drop.
1545     *
1546     * @param info The PendingAppWidgetInfo of the widget being added.
1547     * @param screen The screen where it should be added
1548     * @param cell The cell it should be added to, optional
1549     * @param position The location on the screen where it was dropped, optional
1550     */
1551    void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, int screen,
1552            int[] cell, int[] loc) {
1553        resetAddInfo();
1554        mPendingAddInfo.container = info.container = container;
1555        mPendingAddInfo.screen = info.screen = screen;
1556        mPendingAddInfo.dropPos = loc;
1557        if (cell != null) {
1558            mPendingAddInfo.cellX = cell[0];
1559            mPendingAddInfo.cellY = cell[1];
1560        }
1561
1562        int appWidgetId = getAppWidgetHost().allocateAppWidgetId();
1563        AppWidgetManager.getInstance(this).bindAppWidgetId(appWidgetId, info.componentName);
1564        addAppWidgetImpl(appWidgetId, info);
1565    }
1566
1567    void processShortcut(Intent intent) {
1568        // Handle case where user selected "Applications"
1569        String applicationName = getResources().getString(R.string.group_applications);
1570        String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1571
1572        if (applicationName != null && applicationName.equals(shortcutName)) {
1573            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1574            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1575
1576            Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1577            pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1578            pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application));
1579            startActivityForResultSafely(pickIntent, REQUEST_PICK_APPLICATION);
1580        } else {
1581            startActivityForResultSafely(intent, REQUEST_CREATE_SHORTCUT);
1582        }
1583    }
1584
1585    void processWallpaper(Intent intent) {
1586        startActivityForResult(intent, REQUEST_PICK_WALLPAPER);
1587    }
1588
1589    FolderIcon addFolder(CellLayout layout, long container, final int screen, int cellX,
1590            int cellY) {
1591        final FolderInfo folderInfo = new FolderInfo();
1592        folderInfo.title = getText(R.string.folder_name);
1593
1594        // Update the model
1595        LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screen, cellX, cellY,
1596                false);
1597        sFolders.put(folderInfo.id, folderInfo);
1598
1599        // Create the view
1600        FolderIcon newFolder =
1601            FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache);
1602        mWorkspace.addInScreen(newFolder, container, screen, cellX, cellY, 1, 1,
1603                isWorkspaceLocked());
1604        return newFolder;
1605    }
1606
1607    void removeFolder(FolderInfo folder) {
1608        sFolders.remove(folder.id);
1609    }
1610
1611    private void showNotifications() {
1612        final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1613        if (statusBar != null) {
1614            statusBar.expand();
1615        }
1616    }
1617
1618    private void startWallpaper() {
1619        showWorkspace(true);
1620        final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1621        Intent chooser = Intent.createChooser(pickWallpaper,
1622                getText(R.string.chooser_wallpaper));
1623        // NOTE: Adds a configure option to the chooser if the wallpaper supports it
1624        //       Removed in Eclair MR1
1625//        WallpaperManager wm = (WallpaperManager)
1626//                getSystemService(Context.WALLPAPER_SERVICE);
1627//        WallpaperInfo wi = wm.getWallpaperInfo();
1628//        if (wi != null && wi.getSettingsActivity() != null) {
1629//            LabeledIntent li = new LabeledIntent(getPackageName(),
1630//                    R.string.configure_wallpaper, 0);
1631//            li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
1632//            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
1633//        }
1634        startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
1635    }
1636
1637    /**
1638     * Registers various content observers. The current implementation registers
1639     * only a favorites observer to keep track of the favorites applications.
1640     */
1641    private void registerContentObservers() {
1642        ContentResolver resolver = getContentResolver();
1643        resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
1644                true, mWidgetObserver);
1645    }
1646
1647    @Override
1648    public boolean dispatchKeyEvent(KeyEvent event) {
1649        if (event.getAction() == KeyEvent.ACTION_DOWN) {
1650            switch (event.getKeyCode()) {
1651                case KeyEvent.KEYCODE_HOME:
1652                    return true;
1653                case KeyEvent.KEYCODE_VOLUME_DOWN:
1654                    if (SystemProperties.getInt("debug.launcher2.dumpstate", 0) != 0) {
1655                        dumpState();
1656                        return true;
1657                    }
1658                    break;
1659            }
1660        } else if (event.getAction() == KeyEvent.ACTION_UP) {
1661            switch (event.getKeyCode()) {
1662                case KeyEvent.KEYCODE_HOME:
1663                    return true;
1664            }
1665        }
1666
1667        return super.dispatchKeyEvent(event);
1668    }
1669
1670    @Override
1671    public void onBackPressed() {
1672        if (mState == State.APPS_CUSTOMIZE) {
1673            showWorkspace(true);
1674        } else if (mWorkspace.getOpenFolder() != null) {
1675            Folder openFolder = mWorkspace.getOpenFolder();
1676            if (openFolder.isEditingName()) {
1677                openFolder.dismissEditingName();
1678            } else {
1679                closeFolder();
1680            }
1681        } else {
1682            mWorkspace.exitWidgetResizeMode();
1683
1684            // Back button is a no-op here, but give at least some feedback for the button press
1685            mWorkspace.showOutlinesTemporarily();
1686        }
1687    }
1688
1689    public void closeFolder() {
1690        Folder folder = mWorkspace.getOpenFolder();
1691        if (folder != null) {
1692            closeFolder(folder);
1693        }
1694    }
1695
1696    void closeFolder(Folder folder) {
1697        folder.getInfo().opened = false;
1698
1699        ViewGroup parent = (ViewGroup) folder.getParent().getParent();
1700        if (parent != null) {
1701            FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo);
1702            shrinkAndFadeInFolderIcon(fi);
1703            mDragController.removeDropTarget((DropTarget)folder);
1704        }
1705        folder.animateClosed();
1706    }
1707
1708    /**
1709     * Re-listen when widgets are reset.
1710     */
1711    private void onAppWidgetReset() {
1712        if (mAppWidgetHost != null) {
1713            mAppWidgetHost.startListening();
1714        }
1715    }
1716
1717    /**
1718     * Go through the and disconnect any of the callbacks in the drawables and the views or we
1719     * leak the previous Home screen on orientation change.
1720     */
1721    private void unbindWorkspaceAndHotseatItems() {
1722        LauncherModel.unbindWorkspaceItems();
1723    }
1724
1725    /**
1726     * Launches the intent referred by the clicked shortcut.
1727     *
1728     * @param v The view representing the clicked shortcut.
1729     */
1730    public void onClick(View v) {
1731        Object tag = v.getTag();
1732        if (tag instanceof ShortcutInfo) {
1733            // Open shortcut
1734            final Intent intent = ((ShortcutInfo) tag).intent;
1735            int[] pos = new int[2];
1736            v.getLocationOnScreen(pos);
1737            intent.setSourceBounds(new Rect(pos[0], pos[1],
1738                    pos[0] + v.getWidth(), pos[1] + v.getHeight()));
1739            boolean success = startActivitySafely(intent, tag);
1740
1741            if (success && v instanceof BubbleTextView) {
1742                mWaitingForResume = (BubbleTextView) v;
1743                mWaitingForResume.setStayPressed(true);
1744            }
1745        } else if (tag instanceof FolderInfo) {
1746            if (v instanceof FolderIcon) {
1747                FolderIcon fi = (FolderIcon) v;
1748                handleFolderClick(fi);
1749            }
1750        } else if (v == mAllAppsButton) {
1751            if (mState == State.APPS_CUSTOMIZE) {
1752                showWorkspace(true);
1753            } else {
1754                showAllApps(true);
1755            }
1756        }
1757    }
1758
1759    public boolean onTouch(View v, MotionEvent event) {
1760        // this is an intercepted event being forwarded from mWorkspace;
1761        // clicking anywhere on the workspace causes the customization drawer to slide down
1762        showWorkspace(true);
1763        return false;
1764    }
1765
1766    /**
1767     * Event handler for the search button
1768     *
1769     * @param v The view that was clicked.
1770     */
1771    public void onClickSearchButton(View v) {
1772        startSearch(null, false, null, true);
1773        // Use a custom animation for launching search
1774        overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out_fast);
1775    }
1776
1777    /**
1778     * Event handler for the voice button
1779     *
1780     * @param v The view that was clicked.
1781     */
1782    public void onClickVoiceButton(View v) {
1783        startVoiceSearch();
1784    }
1785
1786    private void startVoiceSearch() {
1787        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1788        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1789        startActivity(intent);
1790    }
1791
1792    /**
1793     * Event handler for the "gear" button that appears on the home screen, which
1794     * enters home screen customization mode.
1795     *
1796     * @param v The view that was clicked.
1797     */
1798    public void onClickConfigureButton(View v) {
1799        addItems();
1800    }
1801
1802    /**
1803     * Event handler for the "grid" button that appears on the home screen, which
1804     * enters all apps mode.
1805     *
1806     * @param v The view that was clicked.
1807     */
1808    public void onClickAllAppsButton(View v) {
1809        showAllApps(true);
1810    }
1811
1812    public void onClickAppMarketButton(View v) {
1813        if (mAppMarketIntent != null) {
1814            startActivitySafely(mAppMarketIntent, "app market");
1815        }
1816    }
1817
1818    void startApplicationDetailsActivity(ComponentName componentName) {
1819        String packageName = componentName.getPackageName();
1820        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
1821                Uri.fromParts("package", packageName, null));
1822        startActivity(intent);
1823    }
1824
1825    void startApplicationUninstallActivity(ApplicationInfo appInfo) {
1826        if ((appInfo.flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) {
1827            // System applications cannot be installed. For now, show a toast explaining that.
1828            // We may give them the option of disabling apps this way.
1829            int messageId = R.string.uninstall_system_app_text;
1830            Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
1831        } else {
1832            String packageName = appInfo.componentName.getPackageName();
1833            String className = appInfo.componentName.getClassName();
1834            Intent intent = new Intent(
1835                    Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
1836            startActivity(intent);
1837        }
1838    }
1839
1840    boolean startActivitySafely(Intent intent, Object tag) {
1841        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1842        try {
1843            startActivity(intent);
1844            return true;
1845        } catch (ActivityNotFoundException e) {
1846            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1847            Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
1848        } catch (SecurityException e) {
1849            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1850            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
1851                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1852                    "or use the exported attribute for this activity. "
1853                    + "tag="+ tag + " intent=" + intent, e);
1854        }
1855        return false;
1856    }
1857
1858    void startActivityForResultSafely(Intent intent, int requestCode) {
1859        try {
1860            startActivityForResult(intent, requestCode);
1861        } catch (ActivityNotFoundException e) {
1862            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1863        } catch (SecurityException e) {
1864            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1865            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
1866                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1867                    "or use the exported attribute for this activity.", e);
1868        }
1869    }
1870
1871    private void handleFolderClick(FolderIcon folderIcon) {
1872        final FolderInfo info = folderIcon.mInfo;
1873        if (!info.opened) {
1874            // Close any open folder
1875            closeFolder();
1876            // Open the requested folder
1877            openFolder(folderIcon);
1878        } else {
1879            // Find the open folder...
1880            Folder openFolder = mWorkspace.getFolderForTag(info);
1881            int folderScreen;
1882            if (openFolder != null) {
1883                folderScreen = mWorkspace.getPageForView(openFolder);
1884                // .. and close it
1885                closeFolder(openFolder);
1886                if (folderScreen != mWorkspace.getCurrentPage()) {
1887                    // Close any folder open on the current screen
1888                    closeFolder();
1889                    // Pull the folder onto this screen
1890                    openFolder(folderIcon);
1891                }
1892            }
1893        }
1894    }
1895
1896    private void growAndFadeOutFolderIcon(FolderIcon fi) {
1897        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
1898        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
1899        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
1900
1901        ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(fi, alpha, scaleX, scaleY);
1902        oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
1903        oa.start();
1904    }
1905
1906    private void shrinkAndFadeInFolderIcon(FolderIcon fi) {
1907        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
1908        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
1909        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
1910
1911        ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(fi, alpha, scaleX, scaleY);
1912        oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
1913        oa.start();
1914    }
1915
1916    /**
1917     * Opens the user folder described by the specified tag. The opening of the folder
1918     * is animated relative to the specified View. If the View is null, no animation
1919     * is played.
1920     *
1921     * @param folderInfo The FolderInfo describing the folder to open.
1922     */
1923    public void openFolder(FolderIcon folderIcon) {
1924        Folder folder = folderIcon.mFolder;
1925        FolderInfo info = folder.mInfo;
1926
1927        growAndFadeOutFolderIcon(folderIcon);
1928        info.opened = true;
1929
1930        mDragLayer.addView(folder);
1931        mDragController.addDropTarget((DropTarget) folder);
1932
1933        folder.animateOpen();
1934        folder.onOpen();
1935    }
1936
1937    public boolean onLongClick(View v) {
1938        if (mState != State.WORKSPACE) {
1939            return false;
1940        }
1941
1942        if (isWorkspaceLocked()) {
1943            return false;
1944        }
1945
1946        if (!(v instanceof CellLayout)) {
1947            v = (View) v.getParent().getParent();
1948        }
1949
1950        resetAddInfo();
1951        CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag();
1952        // This happens when long clicking an item with the dpad/trackball
1953        if (longClickCellInfo == null || !longClickCellInfo.valid) {
1954            return true;
1955        }
1956
1957        // The hotseat touch handling does not go through Workspace, and we always allow long press
1958        // on hotseat items.
1959        final View itemUnderLongClick = longClickCellInfo.cell;
1960        boolean allowLongPress = isHotseatLayout(v) || mWorkspace.allowLongPress();
1961        if (allowLongPress && !mDragController.isDragging()) {
1962            if (itemUnderLongClick == null) {
1963                // User long pressed on empty space
1964                mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1965                        HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1966                addItems();
1967            } else {
1968                if (!(itemUnderLongClick instanceof Folder)) {
1969                    // User long pressed on an item
1970                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1971                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1972                    mWorkspace.startDrag(longClickCellInfo);
1973                }
1974            }
1975        }
1976        return true;
1977    }
1978
1979    boolean isHotseatLayout(View layout) {
1980        return mHotseat != null && layout != null &&
1981                (layout instanceof CellLayout) && (layout == mHotseat.getLayout());
1982    }
1983    Hotseat getHotseat() {
1984        return mHotseat;
1985    }
1986
1987    /**
1988     * Returns the CellLayout of the specified container at the specified screen.
1989     */
1990    CellLayout getCellLayout(long container, int screen) {
1991        if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1992            if (mHotseat != null) {
1993                return mHotseat.getLayout();
1994            } else {
1995                return null;
1996            }
1997        } else {
1998            return (CellLayout) mWorkspace.getChildAt(screen);
1999        }
2000    }
2001
2002    Workspace getWorkspace() {
2003        return mWorkspace;
2004    }
2005
2006    @Override
2007    protected Dialog onCreateDialog(int id) {
2008        switch (id) {
2009            case DIALOG_CREATE_SHORTCUT:
2010                return new CreateShortcut().createDialog();
2011            case DIALOG_RENAME_FOLDER:
2012                return new RenameFolder().createDialog();
2013        }
2014
2015        return super.onCreateDialog(id);
2016    }
2017
2018    @Override
2019    protected void onPrepareDialog(int id, Dialog dialog) {
2020        switch (id) {
2021            case DIALOG_CREATE_SHORTCUT:
2022                break;
2023            case DIALOG_RENAME_FOLDER:
2024                if (mFolderInfo != null) {
2025                    EditText input = (EditText) dialog.findViewById(R.id.folder_name);
2026                    final CharSequence text = mFolderInfo.title;
2027                    input.setText(text);
2028                    input.setSelection(0, text.length());
2029                }
2030                break;
2031        }
2032    }
2033
2034    void showRenameDialog(FolderInfo info) {
2035        mFolderInfo = info;
2036        mWaitingForResult = true;
2037        showDialog(DIALOG_RENAME_FOLDER);
2038    }
2039
2040    private void showAddDialog() {
2041        resetAddInfo();
2042        mPendingAddInfo.container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
2043        mPendingAddInfo.screen = mWorkspace.getCurrentPage();
2044        mWaitingForResult = true;
2045        showDialog(DIALOG_CREATE_SHORTCUT);
2046    }
2047
2048    private void pickShortcut() {
2049        // Insert extra item to handle picking application
2050        Bundle bundle = new Bundle();
2051
2052        ArrayList<String> shortcutNames = new ArrayList<String>();
2053        shortcutNames.add(getString(R.string.group_applications));
2054        bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
2055
2056        ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>();
2057        shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
2058                        R.drawable.ic_launcher_application));
2059        bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
2060
2061        Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
2062        pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(Intent.ACTION_CREATE_SHORTCUT));
2063        pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_shortcut));
2064        pickIntent.putExtras(bundle);
2065
2066        startActivityForResult(pickIntent, REQUEST_PICK_SHORTCUT);
2067    }
2068
2069    private class RenameFolder {
2070        private EditText mInput;
2071
2072        Dialog createDialog() {
2073            final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
2074            mInput = (EditText) layout.findViewById(R.id.folder_name);
2075
2076            AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
2077            builder.setIcon(0);
2078            builder.setTitle(getString(R.string.rename_folder_title));
2079            builder.setCancelable(true);
2080            builder.setOnCancelListener(new Dialog.OnCancelListener() {
2081                public void onCancel(DialogInterface dialog) {
2082                    cleanup();
2083                }
2084            });
2085            builder.setNegativeButton(getString(R.string.cancel_action),
2086                new Dialog.OnClickListener() {
2087                    public void onClick(DialogInterface dialog, int which) {
2088                        cleanup();
2089                    }
2090                }
2091            );
2092            builder.setPositiveButton(getString(R.string.rename_action),
2093                new Dialog.OnClickListener() {
2094                    public void onClick(DialogInterface dialog, int which) {
2095                        changeFolderName();
2096                    }
2097                }
2098            );
2099            builder.setView(layout);
2100
2101            final AlertDialog dialog = builder.create();
2102            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
2103                public void onShow(DialogInterface dialog) {
2104                    mWaitingForResult = true;
2105                    mInput.requestFocus();
2106                    InputMethodManager inputManager = (InputMethodManager)
2107                            getSystemService(Context.INPUT_METHOD_SERVICE);
2108                    inputManager.showSoftInput(mInput, 0);
2109                }
2110            });
2111
2112            return dialog;
2113        }
2114
2115        private void changeFolderName() {
2116            final String name = mInput.getText().toString();
2117            if (!TextUtils.isEmpty(name)) {
2118                // Make sure we have the right folder info
2119                mFolderInfo = sFolders.get(mFolderInfo.id);
2120                mFolderInfo.title = name;
2121                LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
2122
2123                if (mWorkspaceLoading) {
2124                    lockAllApps();
2125                    mModel.startLoader(Launcher.this, false);
2126                } else {
2127                    final FolderIcon folderIcon = (FolderIcon)
2128                            mWorkspace.getViewForTag(mFolderInfo);
2129                    if (folderIcon != null) {
2130                        // TODO: At some point we'll probably want some version of setting
2131                        // the text for a folder icon.
2132                        //folderIcon.setText(name);
2133                        getWorkspace().requestLayout();
2134                    } else {
2135                        lockAllApps();
2136                        mWorkspaceLoading = true;
2137                        mModel.startLoader(Launcher.this, false);
2138                    }
2139                }
2140            }
2141            cleanup();
2142        }
2143
2144        private void cleanup() {
2145            dismissDialog(DIALOG_RENAME_FOLDER);
2146            mWaitingForResult = false;
2147            mFolderInfo = null;
2148        }
2149    }
2150
2151    // Now a part of LauncherModel.Callbacks. Used to reorder loading steps.
2152    public boolean isAllAppsVisible() {
2153        return (mState == State.APPS_CUSTOMIZE);
2154    }
2155
2156    // AllAppsView.Watcher
2157    public void zoomed(float zoom) {
2158        if (zoom == 1.0f) {
2159            mWorkspace.setVisibility(View.GONE);
2160        }
2161    }
2162
2163    /**
2164     * Helper method for the cameraZoomIn/cameraZoomOut animations
2165     * @param view The view being animated
2166     * @param state The state that we are moving in or out of (eg. APPS_CUSTOMIZE)
2167     * @param scaleFactor The scale factor used for the zoom
2168     */
2169    private void setPivotsForZoom(View view, State state, float scaleFactor) {
2170        final int height = view.getHeight();
2171
2172        view.setPivotX(view.getWidth() / 2.0f);
2173        // Set pivotY so that at the starting zoom factor, the view is partially
2174        // visible. Modifying initialHeightFactor changes how much of the view is
2175        // initially showing, and hence the perceived angle from which the view enters.
2176        if (state == State.APPS_CUSTOMIZE) {
2177            final float initialHeightFactor = 0.175f;
2178            view.setPivotY((1 - initialHeightFactor) * height);
2179        } else {
2180            final float initialHeightFactor = 0.2f;
2181            view.setPivotY(-initialHeightFactor * height);
2182        }
2183    }
2184
2185    /**
2186     * Zoom the camera out from the workspace to reveal 'toView'.
2187     * Assumes that the view to show is anchored at either the very top or very bottom
2188     * of the screen.
2189     * @param toState The state to zoom out to. Must be APPS_CUSTOMIZE.
2190     */
2191    private void cameraZoomOut(State toState, boolean animated, final boolean springLoaded) {
2192        final Resources res = getResources();
2193
2194        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
2195        final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
2196        final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
2197        final View toView = mAppsCustomizeTabHost;
2198
2199        setPivotsForZoom(toView, toState, scale);
2200
2201        // Shrink workspaces away if going to AppsCustomize from workspace
2202        mWorkspace.shrink(Workspace.State.SMALL, animated);
2203
2204        if (animated) {
2205            final ValueAnimator scaleAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
2206            scaleAnim.setInterpolator(new Workspace.ZoomOutInterpolator());
2207            scaleAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2208                public void onAnimationUpdate(float a, float b) {
2209                    ((View) toView.getParent()).fastInvalidate();
2210                    toView.setFastScaleX(a * scale + b * 1f);
2211                    toView.setFastScaleY(a * scale + b * 1f);
2212                }
2213            });
2214
2215            toView.setVisibility(View.VISIBLE);
2216            toView.setFastAlpha(0f);
2217            ValueAnimator alphaAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(fadeDuration);
2218            alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
2219            alphaAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2220                public void onAnimationUpdate(float a, float b) {
2221                    // don't need to invalidate because we do so above
2222                    toView.setFastAlpha(a * 0f + b * 1f);
2223                }
2224            });
2225            alphaAnim.start();
2226
2227            if (toView instanceof LauncherTransitionable) {
2228                ((LauncherTransitionable) toView).onLauncherTransitionStart(scaleAnim);
2229            }
2230            scaleAnim.addListener(new AnimatorListenerAdapter() {
2231                @Override
2232                public void onAnimationStart(Animator animation) {
2233                    // Prepare the position
2234                    toView.setTranslationX(0.0f);
2235                    toView.setTranslationY(0.0f);
2236                    toView.setVisibility(View.VISIBLE);
2237                    toView.bringToFront();
2238                }
2239                @Override
2240                public void onAnimationEnd(Animator animation) {
2241                    // If we don't set the final scale values here, if this animation is cancelled
2242                    // it will have the wrong scale value and subsequent cameraPan animations will
2243                    // not fix that
2244                    toView.setScaleX(1.0f);
2245                    toView.setScaleY(1.0f);
2246                    if (toView instanceof LauncherTransitionable) {
2247                        ((LauncherTransitionable) toView).onLauncherTransitionEnd(scaleAnim);
2248                    }
2249
2250                    if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2251                        // Hide the workspace scrollbar
2252                        mWorkspace.hideScrollingIndicator(true);
2253                        mWorkspace.hideScrollIndicatorTrack();
2254                    }
2255                }
2256            });
2257
2258            // toView should appear right at the end of the workspace shrink animation
2259            final int startDelay = 0;
2260
2261            if (mStateAnimation != null) mStateAnimation.cancel();
2262            mStateAnimation = new AnimatorSet();
2263            mStateAnimation.play(scaleAnim).after(startDelay);
2264            mStateAnimation.start();
2265        } else {
2266            toView.setTranslationX(0.0f);
2267            toView.setTranslationY(0.0f);
2268            toView.setScaleX(1.0f);
2269            toView.setScaleY(1.0f);
2270            toView.setVisibility(View.VISIBLE);
2271            toView.bringToFront();
2272            if (toView instanceof LauncherTransitionable) {
2273                ((LauncherTransitionable) toView).onLauncherTransitionStart(null);
2274                ((LauncherTransitionable) toView).onLauncherTransitionEnd(null);
2275
2276                if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2277                    // Hide the workspace scrollbar
2278                    mWorkspace.hideScrollingIndicator(true);
2279                    mWorkspace.hideScrollIndicatorTrack();
2280                }
2281            }
2282        }
2283    }
2284
2285    /**
2286     * Zoom the camera back into the workspace, hiding 'fromView'.
2287     * This is the opposite of cameraZoomOut.
2288     * @param fromState The current state (must be APPS_CUSTOMIZE).
2289     * @param animated If true, the transition will be animated.
2290     */
2291    private void cameraZoomIn(State fromState, boolean animated, final boolean springLoaded) {
2292        Resources res = getResources();
2293
2294        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime);
2295        final float scaleFactor = (float)
2296                res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
2297        final View fromView = mAppsCustomizeTabHost;
2298
2299        setPivotsForZoom(fromView, fromState, scaleFactor);
2300
2301        if (!springLoaded) {
2302            mWorkspace.unshrink(animated);
2303        }
2304        if (animated) {
2305            if (mStateAnimation != null) mStateAnimation.cancel();
2306            mStateAnimation = new AnimatorSet();
2307
2308            final float oldScaleX = fromView.getScaleX();
2309            final float oldScaleY = fromView.getScaleY();
2310
2311            ValueAnimator scaleAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
2312            scaleAnim.setInterpolator(new Workspace.ZoomInInterpolator());
2313            scaleAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2314                public void onAnimationUpdate(float a, float b) {
2315                    ((View)fromView.getParent()).fastInvalidate();
2316                    fromView.setFastScaleX(a * oldScaleX + b * scaleFactor);
2317                    fromView.setFastScaleY(a * oldScaleY + b * scaleFactor);
2318                }
2319            });
2320            final ValueAnimator alphaAnim = ValueAnimator.ofFloat(0f, 1f);
2321            alphaAnim.setDuration(res.getInteger(R.integer.config_appsCustomizeFadeOutTime));
2322            alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
2323            alphaAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2324                public void onAnimationUpdate(float a, float b) {
2325                    // don't need to invalidate because we do so above
2326                    fromView.setFastAlpha(a * 1f + b * 0f);
2327                }
2328            });
2329            if (fromView instanceof LauncherTransitionable) {
2330                ((LauncherTransitionable) fromView).onLauncherTransitionStart(alphaAnim);
2331            }
2332            alphaAnim.addListener(new AnimatorListenerAdapter() {
2333                @Override
2334                public void onAnimationStart(android.animation.Animator animation) {
2335                    if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2336                        // Show the workspace scrollbar
2337                        mWorkspace.showScrollIndicatorTrack();
2338                        mWorkspace.flashScrollingIndicator();
2339                    }
2340                }
2341                @Override
2342                public void onAnimationEnd(Animator animation) {
2343                    fromView.setVisibility(View.GONE);
2344                    if (fromView instanceof LauncherTransitionable) {
2345                        ((LauncherTransitionable) fromView).onLauncherTransitionEnd(alphaAnim);
2346                    }
2347                }
2348            });
2349
2350            mStateAnimation.playTogether(scaleAnim, alphaAnim);
2351            mStateAnimation.start();
2352        } else {
2353            fromView.setVisibility(View.GONE);
2354            if (fromView instanceof LauncherTransitionable) {
2355                ((LauncherTransitionable) fromView).onLauncherTransitionStart(null);
2356                ((LauncherTransitionable) fromView).onLauncherTransitionEnd(null);
2357
2358                if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2359                    // Show the workspace scrollbar
2360                    mWorkspace.showScrollIndicatorTrack();
2361                    mWorkspace.flashScrollingIndicator();
2362                }
2363            }
2364        }
2365    }
2366
2367    void showWorkspace(boolean animated) {
2368        showWorkspace(animated, null);
2369    }
2370
2371    void showWorkspace(boolean animated, CellLayout layout) {
2372        if (layout != null) {
2373            // always animated, but that's ok since we never specify a layout and
2374            // want no animation
2375            mWorkspace.unshrink(layout);
2376        } else {
2377            mWorkspace.unshrink(animated);
2378        }
2379        if (mState == State.APPS_CUSTOMIZE) {
2380            closeAllApps(animated);
2381        }
2382
2383        // Change the state *after* we've called all the transition code
2384        mState = State.WORKSPACE;
2385
2386        // Resume the auto-advance of widgets
2387        mUserPresent = true;
2388        updateRunning();
2389
2390        // send an accessibility event to announce the context change
2391        getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
2392    }
2393
2394    void enterSpringLoadedDragMode(CellLayout layout) {
2395        if (mState == State.APPS_CUSTOMIZE) {
2396            mWorkspace.enterSpringLoadedDragMode(layout);
2397            cameraZoomIn(State.APPS_CUSTOMIZE, true, true);
2398            mState = State.APPS_CUSTOMIZE_SPRING_LOADED;
2399        }
2400        // Otherwise, we are not in spring loaded mode, so don't do anything.
2401    }
2402    void exitSpringLoadedDragModeDelayed(boolean extendedDelay) {
2403        mWorkspace.postDelayed(new Runnable() {
2404            @Override
2405            public void run() {
2406                exitSpringLoadedDragMode();
2407            }
2408        }, (extendedDelay ?
2409                EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT :
2410                EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT));
2411    }
2412    void exitSpringLoadedDragMode() {
2413        if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
2414            mWorkspace.exitSpringLoadedDragMode(Workspace.State.SMALL);
2415            cameraZoomOut(State.APPS_CUSTOMIZE, true, true);
2416            mState = State.APPS_CUSTOMIZE;
2417        }
2418        // Otherwise, we are not in spring loaded mode, so don't do anything.
2419    }
2420
2421    /**
2422     * Shows the hotseat area.
2423     */
2424    void showHotseat(boolean animated) {
2425        if (!LauncherApplication.isScreenLarge()) {
2426            if (animated) {
2427                int duration = mSearchDeleteBar.getTransitionInDuration();
2428                mHotseat.animate().alpha(1f).setDuration(duration);
2429            } else {
2430                mHotseat.setAlpha(1f);
2431            }
2432        }
2433    }
2434
2435    /**
2436     * Hides the hotseat area.
2437     */
2438    void hideHotseat(boolean animated) {
2439        if (!LauncherApplication.isScreenLarge()) {
2440            if (animated) {
2441                int duration = mSearchDeleteBar.getTransitionOutDuration();
2442                mHotseat.animate().alpha(0f).setDuration(duration);
2443            } else {
2444                mHotseat.setAlpha(0f);
2445            }
2446        }
2447    }
2448
2449    void showAllApps(boolean animated) {
2450        if (mState != State.WORKSPACE) return;
2451
2452        cameraZoomOut(State.APPS_CUSTOMIZE, animated, false);
2453        mAppsCustomizeTabHost.requestFocus();
2454
2455        // Hide the search bar and hotseat
2456        mSearchDeleteBar.hideSearchBar(animated);
2457        hideHotseat(animated);
2458
2459        // Change the state *after* we've called all the transition code
2460        mState = State.APPS_CUSTOMIZE;
2461
2462        // Pause the auto-advance of widgets until we are out of AllApps
2463        mUserPresent = false;
2464        updateRunning();
2465
2466        // Send an accessibility event to announce the context change
2467        getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
2468    }
2469
2470    /**
2471     * Things to test when changing this code.
2472     *   - Home from workspace
2473     *          - from center screen
2474     *          - from other screens
2475     *   - Home from all apps
2476     *          - from center screen
2477     *          - from other screens
2478     *   - Back from all apps
2479     *          - from center screen
2480     *          - from other screens
2481     *   - Launch app from workspace and quit
2482     *          - with back
2483     *          - with home
2484     *   - Launch app from all apps and quit
2485     *          - with back
2486     *          - with home
2487     *   - Go to a screen that's not the default, then all
2488     *     apps, and launch and app, and go back
2489     *          - with back
2490     *          -with home
2491     *   - On workspace, long press power and go back
2492     *          - with back
2493     *          - with home
2494     *   - On all apps, long press power and go back
2495     *          - with back
2496     *          - with home
2497     *   - On workspace, power off
2498     *   - On all apps, power off
2499     *   - Launch an app and turn off the screen while in that app
2500     *          - Go back with home key
2501     *          - Go back with back key  TODO: make this not go to workspace
2502     *          - From all apps
2503     *          - From workspace
2504     *   - Enter and exit car mode (becuase it causes an extra configuration changed)
2505     *          - From all apps
2506     *          - From the center workspace
2507     *          - From another workspace
2508     */
2509    void closeAllApps(boolean animated) {
2510        if (mState == State.APPS_CUSTOMIZE || mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
2511            mWorkspace.setVisibility(View.VISIBLE);
2512            cameraZoomIn(State.APPS_CUSTOMIZE, animated, false);
2513
2514            // Show the search bar and hotseat
2515            mSearchDeleteBar.showSearchBar(animated);
2516            showHotseat(animated);
2517
2518            // Set focus to the AppsCustomize button
2519            if (mAllAppsButton != null) {
2520                mAllAppsButton.requestFocus();
2521            }
2522        }
2523    }
2524
2525    void lockAllApps() {
2526        // TODO
2527    }
2528
2529    void unlockAllApps() {
2530        // TODO
2531    }
2532
2533    /**
2534     * Add an item from all apps or customize onto the given workspace screen.
2535     * If layout is null, add to the current screen.
2536     */
2537    void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) {
2538        if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) {
2539            showOutOfSpaceMessage();
2540        } else {
2541            layout.animateDrop();
2542        }
2543    }
2544
2545    private Drawable getExternalPackageToolbarIcon(ComponentName activityName) {
2546        try {
2547            PackageManager packageManager = getPackageManager();
2548            // Look for the toolbar icon specified in the activity meta-data
2549            Bundle metaData = packageManager.getActivityInfo(
2550                    activityName, PackageManager.GET_META_DATA).metaData;
2551            if (metaData != null) {
2552                int iconResId = metaData.getInt(TOOLBAR_ICON_METADATA_NAME);
2553                if (iconResId != 0) {
2554                    Resources res = packageManager.getResourcesForActivity(activityName);
2555                    return res.getDrawable(iconResId);
2556                }
2557            }
2558        } catch (NameNotFoundException e) {
2559            // This can happen if the activity defines an invalid drawable
2560            Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() +
2561                    " not found", e);
2562        } catch (Resources.NotFoundException nfe) {
2563            // This can happen if the activity defines an invalid drawable
2564            Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(),
2565                    nfe);
2566        }
2567        return null;
2568    }
2569
2570    // if successful in getting icon, return it; otherwise, set button to use default drawable
2571    private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity(
2572            int buttonId, ComponentName activityName, int fallbackDrawableId) {
2573        TextView button = (TextView) findViewById(buttonId);
2574        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName);
2575
2576        // If we were unable to find the icon via the meta-data, use a generic one
2577        if (toolbarIcon == null) {
2578            button.setCompoundDrawablesWithIntrinsicBounds(fallbackDrawableId, 0, 0, 0);
2579            return null;
2580        } else {
2581            button.setCompoundDrawablesWithIntrinsicBounds(toolbarIcon, null, null, null);
2582            return toolbarIcon.getConstantState();
2583        }
2584    }
2585
2586    // if successful in getting icon, return it; otherwise, set button to use default drawable
2587    private Drawable.ConstantState updateButtonWithIconFromExternalActivity(
2588            int buttonId, ComponentName activityName, int fallbackDrawableId) {
2589        ImageView button = (ImageView) findViewById(buttonId);
2590        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName);
2591
2592        // If we were unable to find the icon via the meta-data, use a generic one
2593        if (toolbarIcon == null) {
2594            button.setImageResource(fallbackDrawableId);
2595            return null;
2596        } else {
2597            button.setImageDrawable(toolbarIcon);
2598            return toolbarIcon.getConstantState();
2599        }
2600    }
2601
2602    private void updateTextButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
2603        TextView button = (TextView) findViewById(buttonId);
2604        button.setCompoundDrawables(d.newDrawable(getResources()), null, null, null);
2605    }
2606
2607    private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
2608        ImageView button = (ImageView) findViewById(buttonId);
2609        button.setImageDrawable(d.newDrawable(getResources()));
2610    }
2611
2612    private void updateGlobalSearchIcon() {
2613        final ImageView searchButton = (ImageView) findViewById(R.id.search_button);
2614        final View searchDivider = findViewById(R.id.search_divider);
2615
2616        final SearchManager searchManager =
2617                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
2618        ComponentName activityName = searchManager.getGlobalSearchActivity();
2619        if (activityName != null) {
2620            sGlobalSearchIcon = updateButtonWithIconFromExternalActivity(
2621                    R.id.search_button, activityName, R.drawable.ic_search_normal_holo);
2622            searchButton.setVisibility(View.VISIBLE);
2623            if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE);
2624        } else {
2625            searchButton.setVisibility(View.GONE);
2626            if (searchDivider != null) searchDivider.setVisibility(View.GONE);
2627        }
2628    }
2629
2630    private void updateGlobalSearchIcon(Drawable.ConstantState d) {
2631        updateButtonWithDrawable(R.id.search_button, d);
2632    }
2633
2634    private void updateVoiceSearchIcon() {
2635        final View searchDivider = findViewById(R.id.search_divider);
2636        final View voiceButton = findViewById(R.id.voice_button);
2637
2638        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
2639        ComponentName activityName = intent.resolveActivity(getPackageManager());
2640        if (activityName != null) {
2641            sVoiceSearchIcon = updateButtonWithIconFromExternalActivity(
2642                    R.id.voice_button, activityName, R.drawable.ic_voice_search_holo);
2643            if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE);
2644            voiceButton.setVisibility(View.VISIBLE);
2645        } else {
2646            if (searchDivider != null) searchDivider.setVisibility(View.GONE);
2647            voiceButton.setVisibility(View.GONE);
2648        }
2649    }
2650
2651    private void updateVoiceSearchIcon(Drawable.ConstantState d) {
2652        updateButtonWithDrawable(R.id.voice_button, d);
2653    }
2654
2655    /**
2656     * Sets the app market icon
2657     */
2658    private void updateAppMarketIcon() {
2659        final View marketButton = findViewById(R.id.market_button);
2660        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
2661        // Find the app market activity by resolving an intent.
2662        // (If multiple app markets are installed, it will return the ResolverActivity.)
2663        ComponentName activityName = intent.resolveActivity(getPackageManager());
2664        if (activityName != null) {
2665            mAppMarketIntent = intent;
2666            sAppMarketIcon = updateTextButtonWithIconFromExternalActivity(
2667                    R.id.market_button, activityName, R.drawable.ic_launcher_market_holo);
2668            marketButton.setVisibility(View.VISIBLE);
2669
2670            // Remove the shop icon text in the Phone UI
2671            if (!LauncherApplication.isScreenLarge()) {
2672                ((TextView) marketButton).setText("");
2673            }
2674        } else {
2675            // We should hide and disable the view so that we don't try and restore the visibility
2676            // of it when we swap between drag & normal states from IconDropTarget subclasses.
2677            marketButton.setVisibility(View.GONE);
2678            marketButton.setEnabled(false);
2679        }
2680    }
2681
2682    private void updateAppMarketIcon(Drawable.ConstantState d) {
2683        updateTextButtonWithDrawable(R.id.market_button, d);
2684    }
2685
2686    /**
2687     * Displays the shortcut creation dialog and launches, if necessary, the
2688     * appropriate activity.
2689     */
2690    private class CreateShortcut implements DialogInterface.OnClickListener,
2691            DialogInterface.OnCancelListener, DialogInterface.OnDismissListener,
2692            DialogInterface.OnShowListener {
2693
2694        private AddAdapter mAdapter;
2695
2696        Dialog createDialog() {
2697            mAdapter = new AddAdapter(Launcher.this);
2698
2699            final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this,
2700                    AlertDialog.THEME_HOLO_DARK);
2701            builder.setTitle(getString(R.string.menu_item_add_item));
2702            builder.setAdapter(mAdapter, this);
2703
2704            AlertDialog dialog = builder.create();
2705            dialog.setOnCancelListener(this);
2706            dialog.setOnDismissListener(this);
2707            dialog.setOnShowListener(this);
2708
2709            return dialog;
2710        }
2711
2712        public void onCancel(DialogInterface dialog) {
2713            mWaitingForResult = false;
2714            cleanup();
2715        }
2716
2717        public void onDismiss(DialogInterface dialog) {
2718            mWaitingForResult = false;
2719            cleanup();
2720        }
2721
2722        private void cleanup() {
2723            try {
2724                dismissDialog(DIALOG_CREATE_SHORTCUT);
2725            } catch (Exception e) {
2726                // An exception is thrown if the dialog is not visible, which is fine
2727            }
2728        }
2729
2730        /**
2731         * Handle the action clicked in the "Add to home" dialog.
2732         */
2733        public void onClick(DialogInterface dialog, int which) {
2734            cleanup();
2735
2736            AddAdapter.ListItem item = (AddAdapter.ListItem) mAdapter.getItem(which);
2737            switch (item.actionTag) {
2738                case AddAdapter.ITEM_SHORTCUT: {
2739                    if (mAppsCustomizeTabHost != null) {
2740                        mAppsCustomizeTabHost.selectWidgetsTab();
2741                    }
2742                    showAllApps(true);
2743                    break;
2744                }
2745                case AddAdapter.ITEM_APPLICATION: {
2746                    if (mAppsCustomizeTabHost != null) {
2747                        mAppsCustomizeTabHost.selectAppsTab();
2748                    }
2749                    showAllApps(true);
2750                    break;
2751                }
2752                case AddAdapter.ITEM_APPWIDGET: {
2753                    if (mAppsCustomizeTabHost != null) {
2754                        mAppsCustomizeTabHost.selectWidgetsTab();
2755                    }
2756                    showAllApps(true);
2757                    break;
2758                }
2759                case AddAdapter.ITEM_WALLPAPER: {
2760                    startWallpaper();
2761                    break;
2762                }
2763            }
2764        }
2765
2766        public void onShow(DialogInterface dialog) {
2767            mWaitingForResult = true;
2768        }
2769    }
2770
2771    /**
2772     * Receives notifications when applications are added/removed.
2773     */
2774    private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
2775        @Override
2776        public void onReceive(Context context, Intent intent) {
2777            closeSystemDialogs();
2778            String reason = intent.getStringExtra("reason");
2779            if (!"homekey".equals(reason)) {
2780                boolean animate = true;
2781                if (mPaused || "lock".equals(reason)) {
2782                    animate = false;
2783                }
2784                showWorkspace(animate);
2785            }
2786        }
2787    }
2788
2789    /**
2790     * Receives notifications whenever the appwidgets are reset.
2791     */
2792    private class AppWidgetResetObserver extends ContentObserver {
2793        public AppWidgetResetObserver() {
2794            super(new Handler());
2795        }
2796
2797        @Override
2798        public void onChange(boolean selfChange) {
2799            onAppWidgetReset();
2800        }
2801    }
2802
2803    /**
2804     * If the activity is currently paused, signal that we need to re-run the loader
2805     * in onResume.
2806     *
2807     * This needs to be called from incoming places where resources might have been loaded
2808     * while we are paused.  That is becaues the Configuration might be wrong
2809     * when we're not running, and if it comes back to what it was when we
2810     * were paused, we are not restarted.
2811     *
2812     * Implementation of the method from LauncherModel.Callbacks.
2813     *
2814     * @return true if we are currently paused.  The caller might be able to
2815     * skip some work in that case since we will come back again.
2816     */
2817    public boolean setLoadOnResume() {
2818        if (mPaused) {
2819            Log.i(TAG, "setLoadOnResume");
2820            mOnResumeNeedsLoad = true;
2821            return true;
2822        } else {
2823            return false;
2824        }
2825    }
2826
2827    /**
2828     * Implementation of the method from LauncherModel.Callbacks.
2829     */
2830    public int getCurrentWorkspaceScreen() {
2831        if (mWorkspace != null) {
2832            return mWorkspace.getCurrentPage();
2833        } else {
2834            return SCREEN_COUNT / 2;
2835        }
2836    }
2837
2838
2839    /**
2840     * Refreshes the shortcuts shown on the workspace.
2841     *
2842     * Implementation of the method from LauncherModel.Callbacks.
2843     */
2844    public void startBinding() {
2845        final Workspace workspace = mWorkspace;
2846
2847        mWorkspace.clearDropTargets();
2848        int count = workspace.getChildCount();
2849        for (int i = 0; i < count; i++) {
2850            // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
2851            final CellLayout layoutParent = (CellLayout) workspace.getChildAt(i);
2852            layoutParent.removeAllViewsInLayout();
2853        }
2854        if (mHotseat != null) {
2855            mHotseat.resetLayout();
2856        }
2857
2858        // This wasn't being called before which resulted in a leak of AppWidgetHostViews
2859        unbindWorkspaceAndHotseatItems();
2860    }
2861
2862    /**
2863     * Bind the items start-end from the list.
2864     *
2865     * Implementation of the method from LauncherModel.Callbacks.
2866     */
2867    public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
2868        setLoadOnResume();
2869
2870        final Workspace workspace = mWorkspace;
2871        for (int i=start; i<end; i++) {
2872            final ItemInfo item = shortcuts.get(i);
2873            switch (item.itemType) {
2874                case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2875                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2876                    View shortcut = createShortcut((ShortcutInfo)item);
2877                    workspace.addInScreen(shortcut, item.container, item.screen, item.cellX,
2878                            item.cellY, 1, 1, false);
2879                    break;
2880                case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2881                    FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
2882                            (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
2883                            (FolderInfo) item, mIconCache);
2884                    workspace.addInScreen(newFolder, item.container, item.screen, item.cellX,
2885                            item.cellY, 1, 1, false);
2886                    break;
2887            }
2888        }
2889        workspace.requestLayout();
2890    }
2891
2892    /**
2893     * Implementation of the method from LauncherModel.Callbacks.
2894     */
2895    public void bindFolders(HashMap<Long, FolderInfo> folders) {
2896        setLoadOnResume();
2897        sFolders.clear();
2898        sFolders.putAll(folders);
2899    }
2900
2901    /**
2902     * Add the views for a widget to the workspace.
2903     *
2904     * Implementation of the method from LauncherModel.Callbacks.
2905     */
2906    public void bindAppWidget(LauncherAppWidgetInfo item) {
2907        setLoadOnResume();
2908
2909        final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
2910        if (DEBUG_WIDGETS) {
2911            Log.d(TAG, "bindAppWidget: " + item);
2912        }
2913        final Workspace workspace = mWorkspace;
2914
2915        final int appWidgetId = item.appWidgetId;
2916        final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
2917        if (DEBUG_WIDGETS) {
2918            Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
2919        }
2920
2921        item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
2922
2923        item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
2924        item.hostView.setTag(item);
2925
2926        workspace.addInScreen(item.hostView, item.container, item.screen, item.cellX,
2927                item.cellY, item.spanX, item.spanY, false);
2928
2929        addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
2930
2931        workspace.requestLayout();
2932
2933        if (DEBUG_WIDGETS) {
2934            Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
2935                    + (SystemClock.uptimeMillis()-start) + "ms");
2936        }
2937    }
2938
2939    /**
2940     * Callback saying that there aren't any more items to bind.
2941     *
2942     * Implementation of the method from LauncherModel.Callbacks.
2943     */
2944    public void finishBindingItems() {
2945        setLoadOnResume();
2946
2947        if (mSavedState != null) {
2948            if (!mWorkspace.hasFocus()) {
2949                mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
2950            }
2951            mSavedState = null;
2952        }
2953
2954        if (mSavedInstanceState != null) {
2955            super.onRestoreInstanceState(mSavedInstanceState);
2956            mSavedInstanceState = null;
2957        }
2958
2959        mWorkspaceLoading = false;
2960
2961        // If we received the result of any pending adds while the loader was running (e.g. the
2962        // widget configuration forced an orientation change), process them now.
2963        for (int i = 0; i < sPendingAddList.size(); i++) {
2964            completeAdd(sPendingAddList.get(i));
2965        }
2966        sPendingAddList.clear();
2967    }
2968
2969    /**
2970     * Updates the icons on the launcher that are affected by changes to the package list
2971     * on the device.
2972     */
2973    private void updateIconsAffectedByPackageManagerChanges() {
2974        updateAppMarketIcon();
2975        updateVoiceSearchIcon();
2976    }
2977
2978    @Override
2979    public void bindSearchablesChanged() {
2980        updateGlobalSearchIcon();
2981    }
2982
2983    /**
2984     * Add the icons for all apps.
2985     *
2986     * Implementation of the method from LauncherModel.Callbacks.
2987     */
2988    public void bindAllApplications(ArrayList<ApplicationInfo> apps) {
2989        if (mAppsCustomizeContent != null) {
2990            mAppsCustomizeContent.setApps(apps);
2991        }
2992        updateIconsAffectedByPackageManagerChanges();
2993        updateGlobalSearchIcon();
2994    }
2995
2996    /**
2997     * A package was installed.
2998     *
2999     * Implementation of the method from LauncherModel.Callbacks.
3000     */
3001    public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {
3002        setLoadOnResume();
3003        removeDialog(DIALOG_CREATE_SHORTCUT);
3004
3005        if (mAppsCustomizeContent != null) {
3006            mAppsCustomizeContent.addApps(apps);
3007        }
3008        updateIconsAffectedByPackageManagerChanges();
3009    }
3010
3011    /**
3012     * A package was updated.
3013     *
3014     * Implementation of the method from LauncherModel.Callbacks.
3015     */
3016    public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) {
3017        setLoadOnResume();
3018        removeDialog(DIALOG_CREATE_SHORTCUT);
3019        if (mWorkspace != null) {
3020            mWorkspace.updateShortcuts(apps);
3021        }
3022
3023        if (mAppsCustomizeContent != null) {
3024            mAppsCustomizeContent.updateApps(apps);
3025        }
3026        updateIconsAffectedByPackageManagerChanges();
3027    }
3028
3029    /**
3030     * A package was uninstalled.
3031     *
3032     * Implementation of the method from LauncherModel.Callbacks.
3033     */
3034    public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent) {
3035        removeDialog(DIALOG_CREATE_SHORTCUT);
3036        if (permanent) {
3037            mWorkspace.removeItems(apps);
3038        }
3039
3040        if (mAppsCustomizeContent != null) {
3041            mAppsCustomizeContent.removeApps(apps);
3042        }
3043        updateIconsAffectedByPackageManagerChanges();
3044    }
3045
3046    /**
3047     * A number of packages were updated.
3048     */
3049    public void bindPackagesUpdated() {
3050
3051        if (mAppsCustomizeContent != null) {
3052            mAppsCustomizeContent.onPackagesUpdated();
3053        }
3054    }
3055
3056    private int mapConfigurationOriActivityInfoOri(int configOri) {
3057        final Display d = getWindowManager().getDefaultDisplay();
3058        int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
3059        switch (d.getRotation()) {
3060        case Surface.ROTATION_0:
3061        case Surface.ROTATION_180:
3062            // We are currently in the same basic orientation as the natural orientation
3063            naturalOri = configOri;
3064            break;
3065        case Surface.ROTATION_90:
3066        case Surface.ROTATION_270:
3067            // We are currently in the other basic orientation to the natural orientation
3068            naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
3069                    Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
3070            break;
3071        }
3072
3073        int[] oriMap = {
3074                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
3075                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
3076                ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
3077                ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
3078        };
3079        // Since the map starts at portrait, we need to offset if this device's natural orientation
3080        // is landscape.
3081        int indexOffset = 0;
3082        if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
3083            indexOffset = 1;
3084        }
3085        return oriMap[(d.getRotation() + indexOffset) % 4];
3086    }
3087    public void lockScreenOrientation() {
3088        setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
3089                .getConfiguration().orientation));
3090    }
3091    public void unlockScreenOrientation() {
3092        mHandler.postDelayed(new Runnable() {
3093            public void run() {
3094                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
3095            }
3096        }, mRestoreScreenOrientationDelay);
3097    }
3098
3099    /**
3100     * Prints out out state for debugging.
3101     */
3102    public void dumpState() {
3103        Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this);
3104        Log.d(TAG, "mSavedState=" + mSavedState);
3105        Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
3106        Log.d(TAG, "mRestoring=" + mRestoring);
3107        Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
3108        Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
3109        Log.d(TAG, "sFolders.size=" + sFolders.size());
3110        mModel.dumpState();
3111
3112        if (mAppsCustomizeContent != null) {
3113            mAppsCustomizeContent.dumpState();
3114        }
3115        Log.d(TAG, "END launcher2 dump state");
3116    }
3117}
3118
3119interface LauncherTransitionable {
3120    void onLauncherTransitionStart(Animator animation);
3121    void onLauncherTransitionEnd(Animator animation);
3122}
3123