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