Launcher.java revision 6b879f0a5885274a85333531e091283405d490cc
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            mHomeCustomizationDrawer.setOnTabChangedListener(new OnTabChangeListener() {
316                public void onTabChanged(String tabId) {
317                    // animate the changing of the tab content by fading pages in and out
318                    final Resources res = getResources();
319                    final int duration = res.getInteger(R.integer.config_tabTransitionTime);
320                    final float alpha = mCustomizePagedView.getAlpha();
321                    ValueAnimator alphaAnim = ObjectAnimator.ofFloat(mCustomizePagedView,
322                            "alpha", alpha, 0.0f);
323                    alphaAnim.setDuration(duration);
324                    alphaAnim.addListener(new LauncherAnimatorListenerAdapter() {
325                        @Override
326                        public void onAnimationEndOrCancel(Animator animation) {
327                            String tag = mHomeCustomizationDrawer.getCurrentTabTag();
328                            if (tag == WIDGETS_TAG) {
329                                mCustomizePagedView.setCustomizationFilter(
330                                    CustomizePagedView.CustomizationType.WidgetCustomization);
331                            } else if (tag == APPLICATIONS_TAG) {
332                                mCustomizePagedView.setCustomizationFilter(
333                                        CustomizePagedView.CustomizationType.ApplicationCustomization);
334                            } else if (tag == WALLPAPERS_TAG) {
335                                mCustomizePagedView.setCustomizationFilter(
336                                    CustomizePagedView.CustomizationType.WallpaperCustomization);
337                            } else if (tag == SHORTCUTS_TAG) {
338                                mCustomizePagedView.setCustomizationFilter(
339                                        CustomizePagedView.CustomizationType.ShortcutCustomization);
340                            }
341
342                            final float alpha = mCustomizePagedView.getAlpha();
343                            ValueAnimator alphaAnim = ObjectAnimator.ofFloat(
344                                    mCustomizePagedView, "alpha", alpha, 1.0f);
345                            alphaAnim.setDuration(duration);
346                            alphaAnim.start();
347                        }
348                    });
349                    alphaAnim.start();
350                }
351            });
352        }
353        setupViews();
354
355        registerContentObservers();
356
357        lockAllApps();
358
359        mSavedState = savedInstanceState;
360        restoreState(mSavedState);
361
362        if (PROFILE_STARTUP) {
363            android.os.Debug.stopMethodTracing();
364        }
365
366        if (!mRestoring) {
367            mModel.startLoader(this, true);
368        }
369
370        // For handling default keys
371        mDefaultKeySsb = new SpannableStringBuilder();
372        Selection.setSelection(mDefaultKeySsb, 0);
373
374        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
375        registerReceiver(mCloseSystemDialogsReceiver, filter);
376    }
377
378    private void checkForLocaleChange() {
379        if (sLocaleConfiguration == null) {
380            new AsyncTask<Void, Void, LocaleConfiguration>() {
381                @Override
382                protected LocaleConfiguration doInBackground(Void... unused) {
383                    LocaleConfiguration localeConfiguration = new LocaleConfiguration();
384                    readConfiguration(Launcher.this, localeConfiguration);
385                    return localeConfiguration;
386                }
387
388                @Override
389                protected void onPostExecute(LocaleConfiguration result) {
390                    sLocaleConfiguration = result;
391                    checkForLocaleChange();  // recursive, but now with a locale configuration
392                }
393            }.execute();
394            return;
395        }
396
397        final Configuration configuration = getResources().getConfiguration();
398
399        final String previousLocale = sLocaleConfiguration.locale;
400        final String locale = configuration.locale.toString();
401
402        final int previousMcc = sLocaleConfiguration.mcc;
403        final int mcc = configuration.mcc;
404
405        final int previousMnc = sLocaleConfiguration.mnc;
406        final int mnc = configuration.mnc;
407
408        boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
409
410        if (localeChanged) {
411            sLocaleConfiguration.locale = locale;
412            sLocaleConfiguration.mcc = mcc;
413            sLocaleConfiguration.mnc = mnc;
414
415            mIconCache.flush();
416            loadHotseats();
417
418            final LocaleConfiguration localeConfiguration = sLocaleConfiguration;
419            new Thread("WriteLocaleConfiguration") {
420                @Override
421                public void run() {
422                    writeConfiguration(Launcher.this, localeConfiguration);
423                }
424            }.start();
425        }
426    }
427
428    private static class LocaleConfiguration {
429        public String locale;
430        public int mcc = -1;
431        public int mnc = -1;
432    }
433
434    private static void readConfiguration(Context context, LocaleConfiguration configuration) {
435        DataInputStream in = null;
436        try {
437            in = new DataInputStream(context.openFileInput(PREFERENCES));
438            configuration.locale = in.readUTF();
439            configuration.mcc = in.readInt();
440            configuration.mnc = in.readInt();
441        } catch (FileNotFoundException e) {
442            // Ignore
443        } catch (IOException e) {
444            // Ignore
445        } finally {
446            if (in != null) {
447                try {
448                    in.close();
449                } catch (IOException e) {
450                    // Ignore
451                }
452            }
453        }
454    }
455
456    private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
457        DataOutputStream out = null;
458        try {
459            out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
460            out.writeUTF(configuration.locale);
461            out.writeInt(configuration.mcc);
462            out.writeInt(configuration.mnc);
463            out.flush();
464        } catch (FileNotFoundException e) {
465            // Ignore
466        } catch (IOException e) {
467            //noinspection ResultOfMethodCallIgnored
468            context.getFileStreamPath(PREFERENCES).delete();
469        } finally {
470            if (out != null) {
471                try {
472                    out.close();
473                } catch (IOException e) {
474                    // Ignore
475                }
476            }
477        }
478    }
479
480    static int getScreen() {
481        synchronized (sLock) {
482            return sScreen;
483        }
484    }
485
486    static void setScreen(int screen) {
487        synchronized (sLock) {
488            sScreen = screen;
489        }
490    }
491
492    private void setWallpaperDimension() {
493        WallpaperManager wpm = (WallpaperManager)getSystemService(WALLPAPER_SERVICE);
494
495        Display display = getWindowManager().getDefaultDisplay();
496        // TODO: Put back when we decide about scrolling the wallpaper
497        // boolean isPortrait = display.getWidth() < display.getHeight();
498        // final int width = isPortrait ? display.getWidth() : display.getHeight();
499        // final int height = isPortrait ? display.getHeight() : display.getWidth();
500        wpm.suggestDesiredDimensions(Math.max(display.getWidth(), display.getHeight()),
501                Math.max(display.getWidth(), display.getHeight()));
502    }
503
504    // Note: This doesn't do all the client-id magic that BrowserProvider does
505    // in Browser. (http://b/2425179)
506    private Uri getDefaultBrowserUri() {
507        String url = getString(R.string.default_browser_url);
508        if (url.indexOf("{CID}") != -1) {
509            url = url.replace("{CID}", "android-google");
510        }
511        return Uri.parse(url);
512    }
513
514    // Load the Intent templates from arrays.xml to populate the hotseats. For
515    // each Intent, if it resolves to a single app, use that as the launch
516    // intent & use that app's label as the contentDescription. Otherwise,
517    // retain the ResolveActivity so the user can pick an app.
518    private void loadHotseats() {
519        if (mHotseatConfig == null) {
520            mHotseatConfig = getResources().getStringArray(R.array.hotseats);
521            if (mHotseatConfig.length > 0) {
522                mHotseats = new Intent[mHotseatConfig.length];
523                mHotseatLabels = new CharSequence[mHotseatConfig.length];
524                mHotseatIcons = new Drawable[mHotseatConfig.length];
525            } else {
526                mHotseats = null;
527                mHotseatIcons = null;
528                mHotseatLabels = null;
529            }
530
531            TypedArray hotseatIconDrawables = getResources().obtainTypedArray(R.array.hotseat_icons);
532            for (int i=0; i<mHotseatConfig.length; i++) {
533                // load icon for this slot; currently unrelated to the actual activity
534                try {
535                    mHotseatIcons[i] = hotseatIconDrawables.getDrawable(i);
536                } catch (ArrayIndexOutOfBoundsException ex) {
537                    Log.w(TAG, "Missing hotseat_icons array item #" + i);
538                    mHotseatIcons[i] = null;
539                }
540            }
541            hotseatIconDrawables.recycle();
542        }
543
544        PackageManager pm = getPackageManager();
545        for (int i=0; i<mHotseatConfig.length; i++) {
546            Intent intent = null;
547            if (mHotseatConfig[i].equals("*BROWSER*")) {
548                // magic value meaning "launch user's default web browser"
549                // replace it with a generic web request so we can see if there is indeed a default
550                String defaultUri = getString(R.string.default_browser_url);
551                intent = new Intent(
552                        Intent.ACTION_VIEW,
553                        ((defaultUri != null)
554                            ? Uri.parse(defaultUri)
555                            : getDefaultBrowserUri())
556                    ).addCategory(Intent.CATEGORY_BROWSABLE);
557                // note: if the user launches this without a default set, she
558                // will always be taken to the default URL above; this is
559                // unavoidable as we must specify a valid URL in order for the
560                // chooser to appear, and once the user selects something, that
561                // URL is unavoidably sent to the chosen app.
562            } else {
563                try {
564                    intent = Intent.parseUri(mHotseatConfig[i], 0);
565                } catch (java.net.URISyntaxException ex) {
566                    Log.w(TAG, "Invalid hotseat intent: " + mHotseatConfig[i]);
567                    // bogus; leave intent=null
568                }
569            }
570
571            if (intent == null) {
572                mHotseats[i] = null;
573                mHotseatLabels[i] = getText(R.string.activity_not_found);
574                continue;
575            }
576
577            if (LOGD) {
578                Log.d(TAG, "loadHotseats: hotseat " + i
579                    + " initial intent=["
580                    + intent.toUri(Intent.URI_INTENT_SCHEME)
581                    + "]");
582            }
583
584            ResolveInfo bestMatch = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
585            List<ResolveInfo> allMatches = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
586            if (LOGD) {
587                Log.d(TAG, "Best match for intent: " + bestMatch);
588                Log.d(TAG, "All matches: ");
589                for (ResolveInfo ri : allMatches) {
590                    Log.d(TAG, "  --> " + ri);
591                }
592            }
593            // did this resolve to a single app, or the resolver?
594            if (allMatches.size() == 0 || bestMatch == null) {
595                // can't find any activity to handle this. let's leave the
596                // intent as-is and let Launcher show a toast when it fails
597                // to launch.
598                mHotseats[i] = intent;
599
600                // set accessibility text to "Not installed"
601                mHotseatLabels[i] = getText(R.string.activity_not_found);
602            } else {
603                boolean found = false;
604                for (ResolveInfo ri : allMatches) {
605                    if (bestMatch.activityInfo.name.equals(ri.activityInfo.name)
606                        && bestMatch.activityInfo.applicationInfo.packageName
607                            .equals(ri.activityInfo.applicationInfo.packageName)) {
608                        found = true;
609                        break;
610                    }
611                }
612
613                if (!found) {
614                    if (LOGD) Log.d(TAG, "Multiple options, no default yet");
615                    // the bestMatch is probably the ResolveActivity, meaning the
616                    // user has not yet selected a default
617                    // so: we'll keep the original intent for now
618                    mHotseats[i] = intent;
619
620                    // set the accessibility text to "Select shortcut"
621                    mHotseatLabels[i] = getText(R.string.title_select_shortcut);
622                } else {
623                    // we have an app!
624                    // now reconstruct the intent to launch it through the front
625                    // door
626                    ComponentName com = new ComponentName(
627                        bestMatch.activityInfo.applicationInfo.packageName,
628                        bestMatch.activityInfo.name);
629                    mHotseats[i] = new Intent(Intent.ACTION_MAIN).setComponent(com);
630
631                    // load the app label for accessibility
632                    mHotseatLabels[i] = bestMatch.activityInfo.loadLabel(pm);
633                }
634            }
635
636            if (LOGD) {
637                Log.d(TAG, "loadHotseats: hotseat " + i
638                    + " final intent=["
639                    + ((mHotseats[i] == null)
640                        ? "null"
641                        : mHotseats[i].toUri(Intent.URI_INTENT_SCHEME))
642                    + "] label=[" + mHotseatLabels[i]
643                    + "]"
644                    );
645            }
646        }
647    }
648
649    @Override
650    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
651        mWaitingForResult = false;
652
653        // The pattern used here is that a user PICKs a specific application,
654        // which, depending on the target, might need to CREATE the actual target.
655
656        // For example, the user would PICK_SHORTCUT for "Music playlist", and we
657        // launch over to the Music app to actually CREATE_SHORTCUT.
658
659        if (resultCode == RESULT_OK && mAddScreen != -1) {
660            switch (requestCode) {
661                case REQUEST_PICK_APPLICATION:
662                    completeAddApplication(
663                            this, data, mAddScreen, mAddIntersectCellX, mAddIntersectCellY);
664                    break;
665                case REQUEST_PICK_SHORTCUT:
666                    processShortcut(data);
667                    break;
668                case REQUEST_CREATE_SHORTCUT:
669                    completeAddShortcut(data, mAddScreen, mAddIntersectCellX, mAddIntersectCellY);
670                    break;
671                case REQUEST_PICK_LIVE_FOLDER:
672                    addLiveFolder(data);
673                    break;
674                case REQUEST_CREATE_LIVE_FOLDER:
675                    completeAddLiveFolder(data, mAddScreen, mAddIntersectCellX, mAddIntersectCellY);
676                    break;
677                case REQUEST_PICK_APPWIDGET:
678                    addAppWidgetFromPick(data);
679                    break;
680                case REQUEST_CREATE_APPWIDGET:
681                    int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
682                    completeAddAppWidget(appWidgetId, mAddScreen);
683                    break;
684                case REQUEST_PICK_WALLPAPER:
685                    // We just wanted the activity result here so we can clear mWaitingForResult
686                    break;
687            }
688        } else if ((requestCode == REQUEST_PICK_APPWIDGET ||
689                requestCode == REQUEST_CREATE_APPWIDGET) && resultCode == RESULT_CANCELED &&
690                data != null) {
691            // Clean up the appWidgetId if we canceled
692            int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
693            if (appWidgetId != -1) {
694                mAppWidgetHost.deleteAppWidgetId(appWidgetId);
695            }
696        }
697    }
698
699    @Override
700    protected void onResume() {
701        super.onResume();
702        mPaused = false;
703        if (mRestoring || mOnResumeNeedsLoad) {
704            mWorkspaceLoading = true;
705            mModel.startLoader(this, true);
706            mRestoring = false;
707            mOnResumeNeedsLoad = false;
708        }
709        // When we resume Launcher, a different Activity might be responsible for the app
710        // market intent, so refresh the icon
711        updateAppMarketIcon();
712    }
713
714    @Override
715    protected void onPause() {
716        super.onPause();
717        // Some launcher layouts don't have a previous and next view
718        if (mPreviousView != null) {
719            dismissPreview(mPreviousView);
720        }
721        if (mNextView != null) {
722            dismissPreview(mNextView);
723        }
724        mPaused = true;
725        mDragController.cancelDrag();
726    }
727
728    @Override
729    public Object onRetainNonConfigurationInstance() {
730        // Flag the loader to stop early before switching
731        mModel.stopLoader();
732        mAllAppsGrid.surrender();
733        return Boolean.TRUE;
734    }
735
736    // We can't hide the IME if it was forced open.  So don't bother
737    /*
738    @Override
739    public void onWindowFocusChanged(boolean hasFocus) {
740        super.onWindowFocusChanged(hasFocus);
741
742        if (hasFocus) {
743            final InputMethodManager inputManager = (InputMethodManager)
744                    getSystemService(Context.INPUT_METHOD_SERVICE);
745            WindowManager.LayoutParams lp = getWindow().getAttributes();
746            inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new
747                        android.os.Handler()) {
748                        protected void onReceiveResult(int resultCode, Bundle resultData) {
749                            Log.d(TAG, "ResultReceiver got resultCode=" + resultCode);
750                        }
751                    });
752            Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged");
753        }
754    }
755    */
756
757    private boolean acceptFilter() {
758        final InputMethodManager inputManager = (InputMethodManager)
759                getSystemService(Context.INPUT_METHOD_SERVICE);
760        return !inputManager.isFullscreenMode();
761    }
762
763    @Override
764    public boolean onKeyDown(int keyCode, KeyEvent event) {
765        boolean handled = super.onKeyDown(keyCode, event);
766        if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) {
767            boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
768                    keyCode, event);
769            if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
770                // something usable has been typed - start a search
771                // the typed text will be retrieved and cleared by
772                // showSearchDialog()
773                // If there are multiple keystrokes before the search dialog takes focus,
774                // onSearchRequested() will be called for every keystroke,
775                // but it is idempotent, so it's fine.
776                return onSearchRequested();
777            }
778        }
779
780        // Eat the long press event so the keyboard doesn't come up.
781        if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
782            return true;
783        }
784
785        return handled;
786    }
787
788    private String getTypedText() {
789        return mDefaultKeySsb.toString();
790    }
791
792    private void clearTypedText() {
793        mDefaultKeySsb.clear();
794        mDefaultKeySsb.clearSpans();
795        Selection.setSelection(mDefaultKeySsb, 0);
796    }
797
798    /**
799     * Given the integer (ordinal) value of a State enum instance, convert it to a variable of type
800     * State
801     */
802    private static State intToState(int stateOrdinal) {
803        State state = State.WORKSPACE;
804        final State[] stateValues = State.values();
805        for (int i = 0; i < stateValues.length; i++) {
806            if (stateValues[i].ordinal() == stateOrdinal) {
807                state = stateValues[i];
808                break;
809            }
810        }
811        return state;
812    }
813
814    /**
815     * Restores the previous state, if it exists.
816     *
817     * @param savedState The previous state.
818     */
819    private void restoreState(Bundle savedState) {
820        if (savedState == null) {
821            return;
822        }
823
824        State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
825
826        if (state == State.ALL_APPS) {
827            showAllApps(false);
828        } else if (state == State.CUSTOMIZE) {
829            showCustomizationDrawer(false);
830        }
831
832        final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
833        if (currentScreen > -1) {
834            mWorkspace.setCurrentPage(currentScreen);
835        }
836
837        final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
838
839        if (addScreen > -1) {
840            mAddScreen = addScreen;
841            mAddIntersectCellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
842            mAddIntersectCellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
843            mRestoring = true;
844        }
845
846        boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
847        if (renameFolder) {
848            long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
849            mFolderInfo = mModel.getFolderById(this, sFolders, id);
850            mRestoring = true;
851        }
852    }
853
854    /**
855     * Finds all the views we need and configure them properly.
856     */
857    private void setupViews() {
858        final DragController dragController = mDragController;
859
860        DragLayer dragLayer = (DragLayer) findViewById(R.id.drag_layer);
861        dragLayer.setDragController(dragController);
862
863        mAllAppsGrid = (AllAppsView)dragLayer.findViewById(R.id.all_apps_view);
864        mAllAppsGrid.setLauncher(this);
865        mAllAppsGrid.setDragController(dragController);
866        ((View) mAllAppsGrid).setWillNotDraw(false); // We don't want a hole punched in our window.
867        // Manage focusability manually since this thing is always visible (in non-xlarge)
868        ((View) mAllAppsGrid).setFocusable(false);
869
870        if (LauncherApplication.isScreenXLarge()) {
871            // They need to be INVISIBLE initially so that they will be measured in the layout.
872            // Otherwise the animations are messed up when we show them for the first time.
873            ((View) mAllAppsGrid).setVisibility(View.INVISIBLE);
874            mHomeCustomizationDrawer.setVisibility(View.INVISIBLE);
875        }
876
877        mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
878
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 configureButton = findViewById(R.id.configure_button);
2483
2484        switch (newState) {
2485        case WORKSPACE:
2486            hideOrShowToolbarButton(true, searchButton, showSeq);
2487            hideOrShowToolbarButton(true, allAppsButton, showSeq);
2488            hideOrShowToolbarButton(true, configureButton, showSeq);
2489            mDeleteZone.setHandle(allAppsButton);
2490            break;
2491        case ALL_APPS:
2492            hideOrShowToolbarButton(false, configureButton, hideSeq);
2493            hideOrShowToolbarButton(false, searchButton, hideSeq);
2494            hideOrShowToolbarButton(false, allAppsButton, hideSeq);
2495            break;
2496        case CUSTOMIZE:
2497            hideOrShowToolbarButton(false, allAppsButton, hideSeq);
2498            hideOrShowToolbarButton(false, searchButton, hideSeq);
2499            hideOrShowToolbarButton(false, configureButton, hideSeq);
2500            mDeleteZone.setHandle(allAppsButton);
2501            break;
2502        }
2503    }
2504
2505    /**
2506     * Helper method for the cameraZoomIn/cameraZoomOut animations
2507     * @param view The view being animated
2508     * @param state The state that we are moving in or out of -- either ALL_APPS or CUSTOMIZE
2509     * @param scaleFactor The scale factor used for the zoom
2510     */
2511    private void setPivotsForZoom(View view, State state, float scaleFactor) {
2512        final int height = view.getHeight();
2513
2514        view.setPivotX(view.getWidth() / 2.0f);
2515        // Set pivotY so that at the starting zoom factor, the view is partially
2516        // visible. Modifying initialHeightFactor changes how much of the view is
2517        // initially showing, and hence the perceived angle from which the view enters.
2518        final float initialHeightFactor = 0.2f;
2519        if (state == State.ALL_APPS) {
2520            view.setPivotY((1 + initialHeightFactor) * height);
2521        } else {
2522            view.setPivotY(-initialHeightFactor * height);
2523        }
2524    }
2525
2526    /**
2527     * Zoom the camera out from the workspace to reveal 'toView'.
2528     * Assumes that the view to show is anchored at either the very top or very bottom
2529     * of the screen.
2530     * @param toState The state to zoom out to. Must be ALL_APPS or CUSTOMIZE.
2531     */
2532    private void cameraZoomOut(State toState, boolean animated) {
2533        final Resources res = getResources();
2534        final int duration = res.getInteger(R.integer.config_allAppsZoomInTime);
2535        final float scale = (float) res.getInteger(R.integer.config_allAppsZoomScaleFactor);
2536        final boolean toAllApps = (toState == State.ALL_APPS);
2537        final View toView = toAllApps ? (View) mAllAppsGrid : mHomeCustomizationDrawer;
2538
2539        setPivotsForZoom(toView, toState, scale);
2540
2541        if (toAllApps) {
2542            mWorkspace.shrinkToBottomHidden(animated);
2543        } else {
2544            mWorkspace.shrinkToTop(animated);
2545        }
2546
2547        if (animated) {
2548            ValueAnimator scaleAnim = ObjectAnimator.ofPropertyValuesHolder(toView,
2549                    PropertyValuesHolder.ofFloat("scaleX", scale, 1.0f),
2550                    PropertyValuesHolder.ofFloat("scaleY", scale, 1.0f));
2551            scaleAnim.setDuration(duration);
2552
2553            scaleAnim.setInterpolator(new Workspace.ZoomOutInterpolator());
2554            scaleAnim.addListener(new LauncherAnimatorListenerAdapter() {
2555                @Override
2556                public void onAnimationStart(Animator animation) {
2557                    // Prepare the position
2558                    toView.setTranslationX(0.0f);
2559                    toView.setTranslationY(0.0f);
2560                    toView.setVisibility(View.VISIBLE);
2561                    toView.setAlpha(1.0f);
2562                }
2563                @Override
2564                public void onAnimationEndOrCancel(Animator animation) {
2565                    // If we don't set the final scale values here, if this animation is cancelled
2566                    // it will have the wrong scale value and subsequent cameraPan animations will
2567                    // not fix that
2568                    toView.setScaleX(1.0f);
2569                    toView.setScaleY(1.0f);
2570                }
2571            });
2572
2573            AnimatorSet toolbarHideAnim = new AnimatorSet();
2574            AnimatorSet toolbarShowAnim = new AnimatorSet();
2575            hideAndShowToolbarButtons(toState, toolbarShowAnim, toolbarHideAnim);
2576
2577            // toView should appear right at the end of the workspace shrink animation
2578            final int startDelay = res.getInteger(R.integer.config_workspaceShrinkTime) - duration;
2579
2580            if (mStateAnimation != null) mStateAnimation.cancel();
2581            mStateAnimation = new AnimatorSet();
2582            mStateAnimation.playTogether(scaleAnim, toolbarHideAnim);
2583            mStateAnimation.play(scaleAnim).after(startDelay);
2584
2585            // Show the new toolbar buttons just as the main animation is ending
2586            final int fadeInTime = res.getInteger(R.integer.config_toolbarButtonFadeInTime);
2587            mStateAnimation.play(toolbarShowAnim).after(duration + startDelay - fadeInTime);
2588            mStateAnimation.start();
2589        } else {
2590            toView.setTranslationX(0.0f);
2591            toView.setTranslationY(0.0f);
2592            toView.setScaleX(1.0f);
2593            toView.setScaleY(1.0f);
2594            toView.setVisibility(View.VISIBLE);
2595            hideAndShowToolbarButtons(toState, null, null);
2596        }
2597    }
2598
2599    /**
2600     * Zoom the camera back into the workspace, hiding 'fromView'.
2601     * This is the opposite of cameraZoomOut.
2602     * @param fromState The current state (must be ALL_APPS or CUSTOMIZE).
2603     * @param animated If true, the transition will be animated.
2604     */
2605    private void cameraZoomIn(State fromState, boolean animated) {
2606        Resources res = getResources();
2607        int duration = res.getInteger(R.integer.config_allAppsZoomOutTime);
2608        float scaleFactor = (float) res.getInteger(R.integer.config_allAppsZoomScaleFactor);
2609        final View fromView =
2610            (fromState == State.ALL_APPS) ? (View) mAllAppsGrid : mHomeCustomizationDrawer;
2611
2612        mCustomizePagedView.endChoiceMode();
2613        mAllAppsPagedView.endChoiceMode();
2614
2615        setPivotsForZoom(fromView, fromState, scaleFactor);
2616
2617        mWorkspace.unshrink(animated);
2618
2619        if (animated) {
2620            if (mStateAnimation != null) mStateAnimation.cancel();
2621            mStateAnimation = new AnimatorSet();
2622            ValueAnimator scaleAnim = ObjectAnimator.ofPropertyValuesHolder(fromView,
2623                    PropertyValuesHolder.ofFloat("scaleX", scaleFactor),
2624                    PropertyValuesHolder.ofFloat("scaleY", scaleFactor));
2625            scaleAnim.setDuration(duration);
2626            scaleAnim.setInterpolator(new Workspace.ZoomInInterpolator());
2627
2628            ValueAnimator alphaAnim = ObjectAnimator.ofPropertyValuesHolder(fromView,
2629                    PropertyValuesHolder.ofFloat("alpha", 1.0f, 0.0f));
2630            alphaAnim.setDuration(res.getInteger(R.integer.config_allAppsFadeOutTime));
2631            alphaAnim.addListener(new LauncherAnimatorListenerAdapter() {
2632                @Override
2633                public void onAnimationEndOrCancel(Animator animation) {
2634                    fromView.setVisibility(View.GONE);
2635                }
2636            });
2637
2638            AnimatorSet toolbarHideAnim = new AnimatorSet();
2639            AnimatorSet toolbarShowAnim = new AnimatorSet();
2640            hideAndShowToolbarButtons(State.WORKSPACE, toolbarShowAnim, toolbarHideAnim);
2641
2642            mStateAnimation.playTogether(scaleAnim, toolbarHideAnim, alphaAnim);
2643
2644            // Show the new toolbar buttons at the very end of the whole animation
2645            final int fadeInTime = res.getInteger(R.integer.config_toolbarButtonFadeInTime);
2646            final int unshrinkTime = res.getInteger(R.integer.config_workspaceUnshrinkTime);
2647            mStateAnimation.play(toolbarShowAnim).after(unshrinkTime - fadeInTime);
2648            mStateAnimation.start();
2649        } else {
2650            fromView.setVisibility(View.GONE);
2651            hideAndShowToolbarButtons(State.WORKSPACE, null, null);
2652        }
2653    }
2654
2655    /**
2656     * Pan the camera in the vertical plane between 'fromView' and 'toView'.
2657     * This is the transition used on xlarge screens to go between all apps and
2658     * the home customization drawer.
2659     * @param fromState The view to pan away from. Must be ALL_APPS or CUSTOMIZE.
2660     * @param toState The view to pan into the frame. Must be ALL_APPS or CUSTOMIZE.
2661     * @param animated If true, the transition will be animated.
2662     */
2663    private void cameraPan(State fromState, State toState, boolean animated) {
2664        final Resources res = getResources();
2665        final int duration = res.getInteger(R.integer.config_allAppsCameraPanTime);
2666        final int workspaceHeight = mWorkspace.getHeight();
2667
2668        final boolean fromAllApps = (fromState == State.ALL_APPS);
2669        final View fromView = fromAllApps ? (View) mAllAppsGrid : mHomeCustomizationDrawer;
2670        final View toView = fromAllApps ? mHomeCustomizationDrawer : (View) mAllAppsGrid;
2671
2672        final float fromViewStartY = fromAllApps ? 0.0f : fromView.getY();
2673        final float fromViewEndY = fromAllApps ? -fromView.getHeight() * 2 : workspaceHeight * 2;
2674        final float toViewStartY = fromAllApps ? workspaceHeight * 2 : -toView.getHeight() * 2;
2675        final float toViewEndY = fromAllApps ? workspaceHeight - toView.getHeight() : 0.0f;
2676
2677        mCustomizePagedView.endChoiceMode();
2678        mAllAppsPagedView.endChoiceMode();
2679
2680        if (toState == State.ALL_APPS) {
2681            mWorkspace.shrinkToBottomHidden(animated);
2682        } else {
2683            mWorkspace.shrinkToTop(animated);
2684        }
2685
2686        if (animated) {
2687            if (mStateAnimation != null) mStateAnimation.cancel();
2688            mStateAnimation = new AnimatorSet();
2689            mStateAnimation.addListener(new LauncherAnimatorListenerAdapter() {
2690                @Override
2691                public void onAnimationStart(Animator animation) {
2692                    toView.setVisibility(View.VISIBLE);
2693                    toView.setY(toViewStartY);
2694                    toView.setAlpha(1.0f);
2695                }
2696                @Override
2697                public void onAnimationEndOrCancel(Animator animation) {
2698                    fromView.setVisibility(View.GONE);
2699                }
2700            });
2701
2702            AnimatorSet toolbarHideAnim = new AnimatorSet();
2703            AnimatorSet toolbarShowAnim = new AnimatorSet();
2704            hideAndShowToolbarButtons(toState, toolbarShowAnim, toolbarHideAnim);
2705
2706            ObjectAnimator fromAnim = ObjectAnimator.ofFloat(fromView, "y",
2707                    fromViewStartY, fromViewEndY);
2708            fromAnim.setDuration(duration);
2709            ObjectAnimator toAnim = ObjectAnimator.ofPropertyValuesHolder(toView,
2710                    PropertyValuesHolder.ofFloat("y", toViewStartY, toViewEndY),
2711                    PropertyValuesHolder.ofFloat("scaleX", toView.getScaleX(), 1.0f),
2712                    PropertyValuesHolder.ofFloat("scaleY", toView.getScaleY(), 1.0f)
2713                    );
2714            fromAnim.setDuration(duration);
2715            mStateAnimation.playTogether(toolbarHideAnim, fromAnim, toAnim);
2716
2717            // Show the new toolbar buttons just as the main animation is ending
2718            final int fadeInTime = res.getInteger(R.integer.config_toolbarButtonFadeInTime);
2719            mStateAnimation.play(toolbarShowAnim).after(duration - fadeInTime);
2720            mStateAnimation.start();
2721        } else {
2722            fromView.setY(fromViewEndY);
2723            fromView.setVisibility(View.GONE);
2724            toView.setY(toViewEndY);
2725            toView.setScaleX(1.0f);
2726            toView.setScaleY(1.0f);
2727            toView.setVisibility(View.VISIBLE);
2728            hideAndShowToolbarButtons(toState, null, null);
2729        }
2730    }
2731
2732    void showAllApps(boolean animated) {
2733        if (mState == State.ALL_APPS) {
2734            return;
2735        }
2736
2737        if (LauncherApplication.isScreenXLarge()) {
2738            if (mState == State.CUSTOMIZE) {
2739                cameraPan(State.CUSTOMIZE, State.ALL_APPS, animated);
2740            } else {
2741                cameraZoomOut(State.ALL_APPS, animated);
2742            }
2743        } else {
2744            mAllAppsGrid.zoom(1.0f, animated);
2745        }
2746
2747        ((View) mAllAppsGrid).setFocusable(true);
2748        ((View) mAllAppsGrid).requestFocus();
2749
2750        // TODO: fade these two too
2751        mDeleteZone.setVisibility(View.GONE);
2752
2753        // Change the state *after* we've called all the transition code
2754        mState = State.ALL_APPS;
2755    }
2756
2757
2758    void showWorkspace(boolean animated) {
2759        showWorkspace(animated, null);
2760    }
2761
2762    void showWorkspace(boolean animated, CellLayout layout) {
2763        if (layout != null && animated) {
2764            mWorkspace.unshrink(layout);
2765        } else {
2766            mWorkspace.unshrink(animated);
2767        }
2768        if (mState == State.ALL_APPS) {
2769            closeAllApps(animated);
2770        } else if (mState == State.CUSTOMIZE) {
2771            hideCustomizationDrawer(animated);
2772        }
2773
2774        // Change the state *after* we've called all the transition code
2775        mState = State.WORKSPACE;
2776    }
2777
2778    /**
2779     * Things to test when changing this code.
2780     *   - Home from workspace
2781     *          - from center screen
2782     *          - from other screens
2783     *   - Home from all apps
2784     *          - from center screen
2785     *          - from other screens
2786     *   - Back from all apps
2787     *          - from center screen
2788     *          - from other screens
2789     *   - Launch app from workspace and quit
2790     *          - with back
2791     *          - with home
2792     *   - Launch app from all apps and quit
2793     *          - with back
2794     *          - with home
2795     *   - Go to a screen that's not the default, then all
2796     *     apps, and launch and app, and go back
2797     *          - with back
2798     *          -with home
2799     *   - On workspace, long press power and go back
2800     *          - with back
2801     *          - with home
2802     *   - On all apps, long press power and go back
2803     *          - with back
2804     *          - with home
2805     *   - On workspace, power off
2806     *   - On all apps, power off
2807     *   - Launch an app and turn off the screen while in that app
2808     *          - Go back with home key
2809     *          - Go back with back key  TODO: make this not go to workspace
2810     *          - From all apps
2811     *          - From workspace
2812     *   - Enter and exit car mode (becuase it causes an extra configuration changed)
2813     *          - From all apps
2814     *          - From the center workspace
2815     *          - From another workspace
2816     */
2817    void closeAllApps(boolean animated) {
2818        if (mState == State.ALL_APPS) {
2819            mWorkspace.setVisibility(View.VISIBLE);
2820            if (LauncherApplication.isScreenXLarge()) {
2821                cameraZoomIn(State.ALL_APPS, animated);
2822            } else {
2823                mAllAppsGrid.zoom(0.0f, animated);
2824            }
2825            ((View)mAllAppsGrid).setFocusable(false);
2826            mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
2827        }
2828    }
2829
2830    void lockAllApps() {
2831        // TODO
2832    }
2833
2834    void unlockAllApps() {
2835        // TODO
2836    }
2837
2838    // Show the customization drawer (only exists in x-large configuration)
2839    private void showCustomizationDrawer(boolean animated) {
2840        if (mState == State.ALL_APPS) {
2841            cameraPan(State.ALL_APPS, State.CUSTOMIZE, animated);
2842        } else {
2843            cameraZoomOut(State.CUSTOMIZE, animated);
2844        }
2845        // Change the state *after* we've called all the transition code
2846        mState = State.CUSTOMIZE;
2847    }
2848
2849    // Hide the customization drawer (only exists in x-large configuration)
2850    void hideCustomizationDrawer(boolean animated) {
2851        if (mState == State.CUSTOMIZE) {
2852            cameraZoomIn(State.CUSTOMIZE, animated);
2853        }
2854    }
2855
2856    void addExternalItemToScreen(ItemInfo itemInfo, CellLayout layout) {
2857        if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) {
2858            showOutOfSpaceMessage();
2859        }
2860    }
2861
2862    void onWorkspaceClick(CellLayout layout) {
2863        showWorkspace(true, layout);
2864    }
2865
2866    private void updateButtonWithIconFromExternalActivity(
2867            int buttonId, ComponentName activityName, int fallbackDrawableId) {
2868        ImageView button = (ImageView) findViewById(buttonId);
2869        Drawable toolbarIcon = null;
2870        try {
2871            PackageManager packageManager = getPackageManager();
2872            // Look for the toolbar icon specified in the activity meta-data
2873            Bundle metaData = packageManager.getActivityInfo(
2874                    activityName, PackageManager.GET_META_DATA).metaData;
2875            if (metaData != null) {
2876                int iconResId = metaData.getInt(TOOLBAR_ICON_METADATA_NAME);
2877                if (iconResId != 0) {
2878                    Resources res = packageManager.getResourcesForActivity(activityName);
2879                    toolbarIcon = res.getDrawable(iconResId);
2880                }
2881            }
2882        } catch (NameNotFoundException e) {
2883            // Do nothing
2884        }
2885        // If we were unable to find the icon via the meta-data, use a generic one
2886        if (toolbarIcon == null) {
2887            button.setImageResource(fallbackDrawableId);
2888        } else {
2889            button.setImageDrawable(toolbarIcon);
2890        }
2891    }
2892
2893    private void updateGlobalSearchIcon() {
2894        if (LauncherApplication.isScreenXLarge()) {
2895            final SearchManager searchManager =
2896                    (SearchManager) getSystemService(Context.SEARCH_SERVICE);
2897            ComponentName activityName = searchManager.getGlobalSearchActivity();
2898            if (activityName != null) {
2899                updateButtonWithIconFromExternalActivity(
2900                        R.id.search_button, activityName, R.drawable.search_button_generic);
2901            }
2902        }
2903    }
2904
2905    /**
2906     * Sets the app market icon (shown when all apps is visible on x-large screens)
2907     */
2908    private void updateAppMarketIcon() {
2909        if (LauncherApplication.isScreenXLarge()) {
2910            Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
2911            // Find the app market activity by resolving an intent.
2912            // (If multiple app markets are installed, it will return the ResolverActivity.)
2913            ComponentName activityName = intent.resolveActivity(getPackageManager());
2914            if (activityName != null) {
2915                mAppMarketIntent = intent;
2916                updateButtonWithIconFromExternalActivity(
2917                        R.id.market_button, activityName, R.drawable.app_market_generic);
2918            }
2919        }
2920    }
2921
2922    /**
2923     * Displays the shortcut creation dialog and launches, if necessary, the
2924     * appropriate activity.
2925     */
2926    private class CreateShortcut implements DialogInterface.OnClickListener,
2927            DialogInterface.OnCancelListener, DialogInterface.OnDismissListener,
2928            DialogInterface.OnShowListener {
2929
2930        private AddAdapter mAdapter;
2931
2932        Dialog createDialog() {
2933            mAdapter = new AddAdapter(Launcher.this);
2934
2935            final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
2936            builder.setTitle(getString(R.string.menu_item_add_item));
2937            builder.setAdapter(mAdapter, this);
2938
2939            builder.setInverseBackgroundForced(true);
2940
2941            AlertDialog dialog = builder.create();
2942            dialog.setOnCancelListener(this);
2943            dialog.setOnDismissListener(this);
2944            dialog.setOnShowListener(this);
2945
2946            return dialog;
2947        }
2948
2949        public void onCancel(DialogInterface dialog) {
2950            mWaitingForResult = false;
2951            cleanup();
2952        }
2953
2954        public void onDismiss(DialogInterface dialog) {
2955        }
2956
2957        private void cleanup() {
2958            try {
2959                dismissDialog(DIALOG_CREATE_SHORTCUT);
2960            } catch (Exception e) {
2961                // An exception is thrown if the dialog is not visible, which is fine
2962            }
2963        }
2964
2965        /**
2966         * Handle the action clicked in the "Add to home" dialog.
2967         */
2968        public void onClick(DialogInterface dialog, int which) {
2969            Resources res = getResources();
2970            cleanup();
2971
2972            switch (which) {
2973                case AddAdapter.ITEM_SHORTCUT: {
2974                    pickShortcut();
2975                    break;
2976                }
2977
2978                case AddAdapter.ITEM_APPWIDGET: {
2979                    int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId();
2980
2981                    Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
2982                    pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
2983                    // start the pick activity
2984                    startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
2985                    break;
2986                }
2987
2988                case AddAdapter.ITEM_LIVE_FOLDER: {
2989                    // Insert extra item to handle inserting folder
2990                    Bundle bundle = new Bundle();
2991
2992                    ArrayList<String> shortcutNames = new ArrayList<String>();
2993                    shortcutNames.add(res.getString(R.string.group_folder));
2994                    bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
2995
2996                    ArrayList<ShortcutIconResource> shortcutIcons =
2997                            new ArrayList<ShortcutIconResource>();
2998                    shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
2999                            R.drawable.ic_launcher_folder));
3000                    bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
3001
3002                    Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
3003                    pickIntent.putExtra(Intent.EXTRA_INTENT,
3004                            new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER));
3005                    pickIntent.putExtra(Intent.EXTRA_TITLE,
3006                            getText(R.string.title_select_live_folder));
3007                    pickIntent.putExtras(bundle);
3008
3009                    startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);
3010                    break;
3011                }
3012
3013                case AddAdapter.ITEM_WALLPAPER: {
3014                    startWallpaper();
3015                    break;
3016                }
3017            }
3018        }
3019
3020        public void onShow(DialogInterface dialog) {
3021            mWaitingForResult = true;
3022        }
3023    }
3024
3025    /**
3026     * Receives notifications when applications are added/removed.
3027     */
3028    private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
3029        @Override
3030        public void onReceive(Context context, Intent intent) {
3031            closeSystemDialogs();
3032            String reason = intent.getStringExtra("reason");
3033            if (!"homekey".equals(reason)) {
3034                boolean animate = true;
3035                if (mPaused || "lock".equals(reason)) {
3036                    animate = false;
3037                }
3038                showWorkspace(animate);
3039            }
3040        }
3041    }
3042
3043    /**
3044     * Receives notifications whenever the appwidgets are reset.
3045     */
3046    private class AppWidgetResetObserver extends ContentObserver {
3047        public AppWidgetResetObserver() {
3048            super(new Handler());
3049        }
3050
3051        @Override
3052        public void onChange(boolean selfChange) {
3053            onAppWidgetReset();
3054        }
3055    }
3056
3057    /**
3058     * If the activity is currently paused, signal that we need to re-run the loader
3059     * in onResume.
3060     *
3061     * This needs to be called from incoming places where resources might have been loaded
3062     * while we are paused.  That is becaues the Configuration might be wrong
3063     * when we're not running, and if it comes back to what it was when we
3064     * were paused, we are not restarted.
3065     *
3066     * Implementation of the method from LauncherModel.Callbacks.
3067     *
3068     * @return true if we are currently paused.  The caller might be able to
3069     * skip some work in that case since we will come back again.
3070     */
3071    public boolean setLoadOnResume() {
3072        if (mPaused) {
3073            Log.i(TAG, "setLoadOnResume");
3074            mOnResumeNeedsLoad = true;
3075            return true;
3076        } else {
3077            return false;
3078        }
3079    }
3080
3081    /**
3082     * Implementation of the method from LauncherModel.Callbacks.
3083     */
3084    public int getCurrentWorkspaceScreen() {
3085        if (mWorkspace != null) {
3086            return mWorkspace.getCurrentPage();
3087        } else {
3088            return SCREEN_COUNT / 2;
3089        }
3090    }
3091
3092    void setAllAppsPagedView(PagedView view) {
3093        mAllAppsPagedView = view;
3094    }
3095
3096    /**
3097     * Refreshes the shortcuts shown on the workspace.
3098     *
3099     * Implementation of the method from LauncherModel.Callbacks.
3100     */
3101    public void startBinding() {
3102        final Workspace workspace = mWorkspace;
3103        int count = workspace.getChildCount();
3104        for (int i = 0; i < count; i++) {
3105            // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
3106            ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
3107        }
3108
3109        if (DEBUG_USER_INTERFACE) {
3110            android.widget.Button finishButton = new android.widget.Button(this);
3111            finishButton.setText("Finish");
3112            workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
3113
3114            finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
3115                public void onClick(View v) {
3116                    finish();
3117                }
3118            });
3119        }
3120    }
3121
3122    /**
3123     * Bind the items start-end from the list.
3124     *
3125     * Implementation of the method from LauncherModel.Callbacks.
3126     */
3127    public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
3128
3129        setLoadOnResume();
3130
3131        final Workspace workspace = mWorkspace;
3132
3133        for (int i=start; i<end; i++) {
3134            final ItemInfo item = shortcuts.get(i);
3135            mDesktopItems.add(item);
3136            switch (item.itemType) {
3137                case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3138                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3139                    final View shortcut = createShortcut((ShortcutInfo)item);
3140                    workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
3141                            false);
3142                    break;
3143                case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
3144                    final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
3145                            (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
3146                            (UserFolderInfo) item, mIconCache);
3147                    workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
3148                            false);
3149                    break;
3150                case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
3151                    final FolderIcon newLiveFolder = LiveFolderIcon.fromXml(
3152                            R.layout.live_folder_icon, this,
3153                            (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
3154                            (LiveFolderInfo) item);
3155                    workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1,
3156                            false);
3157                    break;
3158            }
3159        }
3160
3161        workspace.requestLayout();
3162    }
3163
3164    /**
3165     * Implementation of the method from LauncherModel.Callbacks.
3166     */
3167    public void bindFolders(HashMap<Long, FolderInfo> folders) {
3168        setLoadOnResume();
3169        sFolders.clear();
3170        sFolders.putAll(folders);
3171    }
3172
3173    /**
3174     * Add the views for a widget to the workspace.
3175     *
3176     * Implementation of the method from LauncherModel.Callbacks.
3177     */
3178    public void bindAppWidget(LauncherAppWidgetInfo item) {
3179        setLoadOnResume();
3180
3181        final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
3182        if (DEBUG_WIDGETS) {
3183            Log.d(TAG, "bindAppWidget: " + item);
3184        }
3185        final Workspace workspace = mWorkspace;
3186
3187        final int appWidgetId = item.appWidgetId;
3188        final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
3189        if (DEBUG_WIDGETS) {
3190            Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
3191        }
3192
3193        item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
3194
3195        item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
3196        item.hostView.setTag(item);
3197
3198        workspace.addInScreen(item.hostView, item.screen, item.cellX,
3199                item.cellY, item.spanX, item.spanY, false);
3200
3201        addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
3202
3203        workspace.requestLayout();
3204
3205        mDesktopItems.add(item);
3206
3207        if (DEBUG_WIDGETS) {
3208            Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
3209                    + (SystemClock.uptimeMillis()-start) + "ms");
3210        }
3211    }
3212
3213    /**
3214     * Callback saying that there aren't any more items to bind.
3215     *
3216     * Implementation of the method from LauncherModel.Callbacks.
3217     */
3218    public void finishBindingItems() {
3219        setLoadOnResume();
3220
3221        if (mSavedState != null) {
3222            if (!mWorkspace.hasFocus()) {
3223                mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
3224            }
3225
3226            final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);
3227            if (userFolders != null) {
3228                for (long folderId : userFolders) {
3229                    final FolderInfo info = sFolders.get(folderId);
3230                    if (info != null) {
3231                        openFolder(info);
3232                    }
3233                }
3234                final Folder openFolder = mWorkspace.getOpenFolder();
3235                if (openFolder != null) {
3236                    openFolder.requestFocus();
3237                }
3238            }
3239
3240            mSavedState = null;
3241        }
3242
3243        if (mSavedInstanceState != null) {
3244            super.onRestoreInstanceState(mSavedInstanceState);
3245            mSavedInstanceState = null;
3246        }
3247
3248        mWorkspaceLoading = false;
3249    }
3250
3251    /**
3252     * Add the icons for all apps.
3253     *
3254     * Implementation of the method from LauncherModel.Callbacks.
3255     */
3256    public void bindAllApplications(ArrayList<ApplicationInfo> apps) {
3257        mAllAppsGrid.setApps(apps);
3258        if (mCustomizePagedView != null) {
3259            mCustomizePagedView.setApps(apps);
3260        }
3261        updateAppMarketIcon();
3262        updateGlobalSearchIcon();
3263    }
3264
3265    /**
3266     * A package was installed.
3267     *
3268     * Implementation of the method from LauncherModel.Callbacks.
3269     */
3270    public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {
3271        setLoadOnResume();
3272        removeDialog(DIALOG_CREATE_SHORTCUT);
3273        mAllAppsGrid.addApps(apps);
3274        if (mCustomizePagedView != null) {
3275            mCustomizePagedView.addApps(apps);
3276        }
3277        updateAppMarketIcon();
3278        updateGlobalSearchIcon();
3279    }
3280
3281    /**
3282     * A package was updated.
3283     *
3284     * Implementation of the method from LauncherModel.Callbacks.
3285     */
3286    public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) {
3287        setLoadOnResume();
3288        removeDialog(DIALOG_CREATE_SHORTCUT);
3289        mWorkspace.updateShortcuts(apps);
3290        mAllAppsGrid.updateApps(apps);
3291        if (mCustomizePagedView != null) {
3292            mCustomizePagedView.updateApps(apps);
3293        }
3294        updateAppMarketIcon();
3295        updateGlobalSearchIcon();
3296    }
3297
3298    /**
3299     * A package was uninstalled.
3300     *
3301     * Implementation of the method from LauncherModel.Callbacks.
3302     */
3303    public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent) {
3304        removeDialog(DIALOG_CREATE_SHORTCUT);
3305        if (permanent) {
3306            mWorkspace.removeItems(apps);
3307        }
3308        mAllAppsGrid.removeApps(apps);
3309        if (mCustomizePagedView != null) {
3310            mCustomizePagedView.removeApps(apps);
3311        }
3312        updateAppMarketIcon();
3313        updateGlobalSearchIcon();
3314    }
3315
3316    /**
3317     * A number of packages were updated.
3318     */
3319    public void bindPackagesUpdated() {
3320        // update the customization drawer contents
3321        if (mCustomizePagedView != null) {
3322            mCustomizePagedView.update();
3323        }
3324    }
3325
3326    /**
3327     * Prints out out state for debugging.
3328     */
3329    public void dumpState() {
3330        Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this);
3331        Log.d(TAG, "mSavedState=" + mSavedState);
3332        Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
3333        Log.d(TAG, "mRestoring=" + mRestoring);
3334        Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
3335        Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
3336        Log.d(TAG, "mDesktopItems.size=" + mDesktopItems.size());
3337        Log.d(TAG, "sFolders.size=" + sFolders.size());
3338        mModel.dumpState();
3339        mAllAppsGrid.dumpState();
3340        Log.d(TAG, "END launcher2 dump state");
3341    }
3342}
3343