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