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