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