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