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