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