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