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