Launcher.java revision a113121fd3c43f1e1d23064e17c540c48fe330cc
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 android.accounts.Account;
21import android.accounts.AccountManager;
22import android.animation.Animator;
23import android.animation.AnimatorListenerAdapter;
24import android.animation.AnimatorSet;
25import android.animation.ObjectAnimator;
26import android.animation.PropertyValuesHolder;
27import android.animation.ValueAnimator;
28import android.animation.ValueAnimator.AnimatorUpdateListener;
29import android.app.Activity;
30import android.app.ActivityManager;
31import android.app.ActivityOptions;
32import android.app.SearchManager;
33import android.appwidget.AppWidgetHostView;
34import android.appwidget.AppWidgetManager;
35import android.appwidget.AppWidgetProviderInfo;
36import android.content.ActivityNotFoundException;
37import android.content.BroadcastReceiver;
38import android.content.ComponentCallbacks2;
39import android.content.ComponentName;
40import android.content.ContentResolver;
41import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
44import android.content.SharedPreferences;
45import android.content.pm.ActivityInfo;
46import android.content.pm.PackageManager;
47import android.content.pm.PackageManager.NameNotFoundException;
48import android.content.res.Configuration;
49import android.content.res.Resources;
50import android.database.ContentObserver;
51import android.graphics.Bitmap;
52import android.graphics.Canvas;
53import android.graphics.PorterDuff;
54import android.graphics.Rect;
55import android.graphics.drawable.Drawable;
56import android.net.Uri;
57import android.os.AsyncTask;
58import android.os.Build;
59import android.os.Bundle;
60import android.os.Environment;
61import android.os.Handler;
62import android.os.Message;
63import android.os.StrictMode;
64import android.os.SystemClock;
65import android.provider.Settings;
66import android.speech.RecognizerIntent;
67import android.text.Selection;
68import android.text.SpannableStringBuilder;
69import android.text.TextUtils;
70import android.text.method.TextKeyListener;
71import android.util.Log;
72import android.view.Display;
73import android.view.HapticFeedbackConstants;
74import android.view.KeyEvent;
75import android.view.LayoutInflater;
76import android.view.Menu;
77import android.view.MenuItem;
78import android.view.MotionEvent;
79import android.view.Surface;
80import android.view.View;
81import android.view.View.OnLongClickListener;
82import android.view.ViewGroup;
83import android.view.ViewTreeObserver;
84import android.view.ViewTreeObserver.OnGlobalLayoutListener;
85import android.view.WindowManager;
86import android.view.accessibility.AccessibilityEvent;
87import android.view.animation.AccelerateDecelerateInterpolator;
88import android.view.animation.AccelerateInterpolator;
89import android.view.animation.DecelerateInterpolator;
90import android.view.inputmethod.InputMethodManager;
91import android.widget.Advanceable;
92import android.widget.ImageView;
93import android.widget.TextView;
94import android.widget.Toast;
95
96import com.android.common.Search;
97import com.android.launcher.R;
98import com.android.launcher2.DropTarget.DragObject;
99
100import java.io.DataInputStream;
101import java.io.DataOutputStream;
102import java.io.FileDescriptor;
103import java.io.FileInputStream;
104import java.io.FileNotFoundException;
105import java.io.IOException;
106import java.io.PrintWriter;
107import java.util.ArrayList;
108import java.util.Collection;
109import java.util.Collections;
110import java.util.Comparator;
111import java.util.HashMap;
112import java.util.HashSet;
113import java.util.List;
114import java.util.Set;
115
116/**
117 * Default launcher application.
118 */
119public final class Launcher extends Activity
120        implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
121                   View.OnTouchListener {
122    static final String TAG = "Launcher";
123    static final boolean LOGD = false;
124
125    static final boolean PROFILE_STARTUP = false;
126    static final boolean DEBUG_WIDGETS = false;
127    static final boolean DEBUG_STRICT_MODE = false;
128
129    private static final int MENU_GROUP_WALLPAPER = 1;
130    private static final int MENU_WALLPAPER_SETTINGS = Menu.FIRST + 1;
131    private static final int MENU_MANAGE_APPS = MENU_WALLPAPER_SETTINGS + 1;
132    private static final int MENU_SYSTEM_SETTINGS = MENU_MANAGE_APPS + 1;
133    private static final int MENU_HELP = MENU_SYSTEM_SETTINGS + 1;
134
135    private static final int REQUEST_CREATE_SHORTCUT = 1;
136    private static final int REQUEST_CREATE_APPWIDGET = 5;
137    private static final int REQUEST_PICK_APPLICATION = 6;
138    private static final int REQUEST_PICK_SHORTCUT = 7;
139    private static final int REQUEST_PICK_APPWIDGET = 9;
140    private static final int REQUEST_PICK_WALLPAPER = 10;
141
142    private static final int REQUEST_BIND_APPWIDGET = 11;
143
144    static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
145
146    static final int SCREEN_COUNT = 5;
147    static final int DEFAULT_SCREEN = 2;
148
149    private static final String PREFERENCES = "launcher.preferences";
150    static final String FORCE_ENABLE_ROTATION_PROPERTY = "debug.force_enable_rotation";
151    static final String DUMP_STATE_PROPERTY = "debug.dumpstate";
152
153    // The Intent extra that defines whether to ignore the launch animation
154    static final String INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION =
155            "com.android.launcher.intent.extra.shortcut.INGORE_LAUNCH_ANIMATION";
156
157    // Type: int
158    private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
159    // Type: int
160    private static final String RUNTIME_STATE = "launcher.state";
161    // Type: int
162    private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container";
163    // Type: int
164    private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
165    // Type: int
166    private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x";
167    // Type: int
168    private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y";
169    // Type: boolean
170    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
171    // Type: long
172    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
173    // Type: int
174    private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_span_x";
175    // Type: int
176    private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_span_y";
177    // Type: parcelable
178    private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_INFO = "launcher.add_widget_info";
179
180    private static final String TOOLBAR_ICON_METADATA_NAME = "com.android.launcher.toolbar_icon";
181    private static final String TOOLBAR_SEARCH_ICON_METADATA_NAME =
182            "com.android.launcher.toolbar_search_icon";
183    private static final String TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME =
184            "com.android.launcher.toolbar_voice_search_icon";
185
186    /** The different states that Launcher can be in. */
187    private enum State { NONE, WORKSPACE, APPS_CUSTOMIZE, APPS_CUSTOMIZE_SPRING_LOADED };
188    private State mState = State.WORKSPACE;
189    private AnimatorSet mStateAnimation;
190    private AnimatorSet mDividerAnimator;
191
192    static final int APPWIDGET_HOST_ID = 1024;
193    private static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300;
194    private static final int EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT = 600;
195    private static final int SHOW_CLING_DURATION = 550;
196    private static final int DISMISS_CLING_DURATION = 250;
197
198    private static final Object sLock = new Object();
199    private static int sScreen = DEFAULT_SCREEN;
200
201    // How long to wait before the new-shortcut animation automatically pans the workspace
202    private static int NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS = 10;
203
204    private final BroadcastReceiver mCloseSystemDialogsReceiver
205            = new CloseSystemDialogsIntentReceiver();
206    private final ContentObserver mWidgetObserver = new AppWidgetResetObserver();
207
208    private LayoutInflater mInflater;
209
210    private Workspace mWorkspace;
211    private View mQsbDivider;
212    private View mDockDivider;
213    private DragLayer mDragLayer;
214    private DragController mDragController;
215
216    private AppWidgetManager mAppWidgetManager;
217    private LauncherAppWidgetHost mAppWidgetHost;
218
219    private ItemInfo mPendingAddInfo = new ItemInfo();
220    private AppWidgetProviderInfo mPendingAddWidgetInfo;
221
222    private int[] mTmpAddItemCellCoordinates = new int[2];
223
224    private FolderInfo mFolderInfo;
225
226    private Hotseat mHotseat;
227    private View mAllAppsButton;
228
229    private SearchDropTargetBar mSearchDropTargetBar;
230    private AppsCustomizeTabHost mAppsCustomizeTabHost;
231    private AppsCustomizePagedView mAppsCustomizeContent;
232    private boolean mAutoAdvanceRunning = false;
233
234    private Bundle mSavedState;
235    // We set the state in both onCreate and then onNewIntent in some cases, which causes both
236    // scroll issues (because the workspace may not have been measured yet) and extra work.
237    // Instead, just save the state that we need to restore Launcher to, and commit it in onResume.
238    private State mOnResumeState = State.NONE;
239
240    private SpannableStringBuilder mDefaultKeySsb = null;
241
242    private boolean mWorkspaceLoading = true;
243
244    private boolean mPaused = true;
245    private boolean mRestoring;
246    private boolean mWaitingForResult;
247    private boolean mOnResumeNeedsLoad;
248
249    // Keep track of whether the user has left launcher
250    private static boolean sPausedFromUserAction = false;
251
252    private Bundle mSavedInstanceState;
253
254    private LauncherModel mModel;
255    private IconCache mIconCache;
256    private boolean mUserPresent = true;
257    private boolean mVisible = false;
258    private boolean mAttached = false;
259
260    private static LocaleConfiguration sLocaleConfiguration = null;
261
262    private static HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
263
264    private Intent mAppMarketIntent = null;
265
266    // Related to the auto-advancing of widgets
267    private final int ADVANCE_MSG = 1;
268    private final int mAdvanceInterval = 20000;
269    private final int mAdvanceStagger = 250;
270    private long mAutoAdvanceSentTime;
271    private long mAutoAdvanceTimeLeft = -1;
272    private HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance =
273        new HashMap<View, AppWidgetProviderInfo>();
274
275    // Determines how long to wait after a rotation before restoring the screen orientation to
276    // match the sensor state.
277    private final int mRestoreScreenOrientationDelay = 500;
278
279    // External icons saved in case of resource changes, orientation, etc.
280    private static Drawable.ConstantState[] sGlobalSearchIcon = new Drawable.ConstantState[2];
281    private static Drawable.ConstantState[] sVoiceSearchIcon = new Drawable.ConstantState[2];
282    private static Drawable.ConstantState[] sAppMarketIcon = new Drawable.ConstantState[2];
283
284    private final ArrayList<Integer> mSynchronouslyBoundPages = new ArrayList<Integer>();
285
286    static final ArrayList<String> sDumpLogs = new ArrayList<String>();
287
288    // We only want to get the SharedPreferences once since it does an FS stat each time we get
289    // it from the context.
290    private SharedPreferences mSharedPrefs;
291
292    // Holds the page that we need to animate to, and the icon views that we need to animate up
293    // when we scroll to that page on resume.
294    private int mNewShortcutAnimatePage = -1;
295    private ArrayList<View> mNewShortcutAnimateViews = new ArrayList<View>();
296    private ImageView mFolderIconImageView;
297    private Bitmap mFolderIconBitmap;
298    private Canvas mFolderIconCanvas;
299    private Rect mRectForFolderAnimation = new Rect();
300
301    private BubbleTextView mWaitingForResume;
302
303    private HideFromAccessibilityHelper mHideFromAccessibilityHelper
304        = new HideFromAccessibilityHelper();
305
306    private Runnable mBuildLayersRunnable = new Runnable() {
307        public void run() {
308            if (mWorkspace != null) {
309                mWorkspace.buildPageHardwareLayers();
310            }
311        }
312    };
313
314    private static ArrayList<PendingAddArguments> sPendingAddList
315            = new ArrayList<PendingAddArguments>();
316
317    private static class PendingAddArguments {
318        int requestCode;
319        Intent intent;
320        long container;
321        int screen;
322        int cellX;
323        int cellY;
324    }
325
326
327    private boolean doesFileExist(String filename) {
328        FileInputStream fis = null;
329        try {
330            fis = openFileInput(filename);
331            fis.close();
332            return true;
333        } catch (java.io.FileNotFoundException e) {
334            return false;
335        } catch (java.io.IOException e) {
336            return true;
337        }
338    }
339
340    @Override
341    protected void onCreate(Bundle savedInstanceState) {
342        if (DEBUG_STRICT_MODE) {
343            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
344                    .detectDiskReads()
345                    .detectDiskWrites()
346                    .detectNetwork()   // or .detectAll() for all detectable problems
347                    .penaltyLog()
348                    .build());
349            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
350                    .detectLeakedSqlLiteObjects()
351                    .detectLeakedClosableObjects()
352                    .penaltyLog()
353                    .penaltyDeath()
354                    .build());
355        }
356
357        super.onCreate(savedInstanceState);
358        LauncherApplication app = ((LauncherApplication)getApplication());
359        mSharedPrefs = getSharedPreferences(LauncherApplication.getSharedPreferencesKey(),
360                Context.MODE_PRIVATE);
361        mModel = app.setLauncher(this);
362        mIconCache = app.getIconCache();
363        mDragController = new DragController(this);
364        mInflater = getLayoutInflater();
365
366        mAppWidgetManager = AppWidgetManager.getInstance(this);
367        mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
368        mAppWidgetHost.startListening();
369
370        // If we are getting an onCreate, we can actually preempt onResume and unset mPaused here,
371        // this also ensures that any synchronous binding below doesn't re-trigger another
372        // LauncherModel load.
373        mPaused = false;
374
375        if (PROFILE_STARTUP) {
376            android.os.Debug.startMethodTracing(
377                    Environment.getExternalStorageDirectory() + "/launcher");
378        }
379
380        checkForLocaleChange();
381        setContentView(R.layout.launcher);
382        setupViews();
383        showFirstRunWorkspaceCling();
384
385        registerContentObservers();
386
387        lockAllApps();
388
389        mSavedState = savedInstanceState;
390        restoreState(mSavedState);
391
392        // Update customization drawer _after_ restoring the states
393        if (mAppsCustomizeContent != null) {
394            mAppsCustomizeContent.onPackagesUpdated();
395        }
396
397        if (PROFILE_STARTUP) {
398            android.os.Debug.stopMethodTracing();
399        }
400
401        if (!mRestoring) {
402            if (sPausedFromUserAction) {
403                // If the user leaves launcher, then we should just load items asynchronously when
404                // they return.
405                mModel.startLoader(true, -1);
406            } else {
407                // We only load the page synchronously if the user rotates (or triggers a
408                // configuration change) while launcher is in the foreground
409                mModel.startLoader(true, mWorkspace.getCurrentPage());
410            }
411        }
412
413        if (!mModel.isAllAppsLoaded()) {
414            ViewGroup appsCustomizeContentParent = (ViewGroup) mAppsCustomizeContent.getParent();
415            mInflater.inflate(R.layout.apps_customize_progressbar, appsCustomizeContentParent);
416        }
417
418        // For handling default keys
419        mDefaultKeySsb = new SpannableStringBuilder();
420        Selection.setSelection(mDefaultKeySsb, 0);
421
422        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
423        registerReceiver(mCloseSystemDialogsReceiver, filter);
424
425        updateGlobalIcons();
426
427        // On large interfaces, we want the screen to auto-rotate based on the current orientation
428        unlockScreenOrientation(true);
429    }
430
431    protected void onUserLeaveHint() {
432        super.onUserLeaveHint();
433        sPausedFromUserAction = true;
434    }
435
436    private void updateGlobalIcons() {
437        boolean searchVisible = false;
438        boolean voiceVisible = false;
439        // If we have a saved version of these external icons, we load them up immediately
440        int coi = getCurrentOrientationIndexForGlobalIcons();
441        if (sGlobalSearchIcon[coi] == null || sVoiceSearchIcon[coi] == null ||
442                sAppMarketIcon[coi] == null) {
443            updateAppMarketIcon();
444            searchVisible = updateGlobalSearchIcon();
445            voiceVisible = updateVoiceSearchIcon(searchVisible);
446        }
447        if (sGlobalSearchIcon[coi] != null) {
448             updateGlobalSearchIcon(sGlobalSearchIcon[coi]);
449             searchVisible = true;
450        }
451        if (sVoiceSearchIcon[coi] != null) {
452            updateVoiceSearchIcon(sVoiceSearchIcon[coi]);
453            voiceVisible = true;
454        }
455        if (sAppMarketIcon[coi] != null) {
456            updateAppMarketIcon(sAppMarketIcon[coi]);
457        }
458        if (mSearchDropTargetBar != null) {
459            mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
460        }
461    }
462
463    private void checkForLocaleChange() {
464        if (sLocaleConfiguration == null) {
465            new AsyncTask<Void, Void, LocaleConfiguration>() {
466                @Override
467                protected LocaleConfiguration doInBackground(Void... unused) {
468                    LocaleConfiguration localeConfiguration = new LocaleConfiguration();
469                    readConfiguration(Launcher.this, localeConfiguration);
470                    return localeConfiguration;
471                }
472
473                @Override
474                protected void onPostExecute(LocaleConfiguration result) {
475                    sLocaleConfiguration = result;
476                    checkForLocaleChange();  // recursive, but now with a locale configuration
477                }
478            }.execute();
479            return;
480        }
481
482        final Configuration configuration = getResources().getConfiguration();
483
484        final String previousLocale = sLocaleConfiguration.locale;
485        final String locale = configuration.locale.toString();
486
487        final int previousMcc = sLocaleConfiguration.mcc;
488        final int mcc = configuration.mcc;
489
490        final int previousMnc = sLocaleConfiguration.mnc;
491        final int mnc = configuration.mnc;
492
493        boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
494
495        if (localeChanged) {
496            sLocaleConfiguration.locale = locale;
497            sLocaleConfiguration.mcc = mcc;
498            sLocaleConfiguration.mnc = mnc;
499
500            mIconCache.flush();
501
502            final LocaleConfiguration localeConfiguration = sLocaleConfiguration;
503            new Thread("WriteLocaleConfiguration") {
504                @Override
505                public void run() {
506                    writeConfiguration(Launcher.this, localeConfiguration);
507                }
508            }.start();
509        }
510    }
511
512    private static class LocaleConfiguration {
513        public String locale;
514        public int mcc = -1;
515        public int mnc = -1;
516    }
517
518    private static void readConfiguration(Context context, LocaleConfiguration configuration) {
519        DataInputStream in = null;
520        try {
521            in = new DataInputStream(context.openFileInput(PREFERENCES));
522            configuration.locale = in.readUTF();
523            configuration.mcc = in.readInt();
524            configuration.mnc = in.readInt();
525        } catch (FileNotFoundException e) {
526            // Ignore
527        } catch (IOException e) {
528            // Ignore
529        } finally {
530            if (in != null) {
531                try {
532                    in.close();
533                } catch (IOException e) {
534                    // Ignore
535                }
536            }
537        }
538    }
539
540    private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
541        DataOutputStream out = null;
542        try {
543            out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
544            out.writeUTF(configuration.locale);
545            out.writeInt(configuration.mcc);
546            out.writeInt(configuration.mnc);
547            out.flush();
548        } catch (FileNotFoundException e) {
549            // Ignore
550        } catch (IOException e) {
551            //noinspection ResultOfMethodCallIgnored
552            context.getFileStreamPath(PREFERENCES).delete();
553        } finally {
554            if (out != null) {
555                try {
556                    out.close();
557                } catch (IOException e) {
558                    // Ignore
559                }
560            }
561        }
562    }
563
564    public DragLayer getDragLayer() {
565        return mDragLayer;
566    }
567
568    boolean isDraggingEnabled() {
569        // We prevent dragging when we are loading the workspace as it is possible to pick up a view
570        // that is subsequently removed from the workspace in startBinding().
571        return !mModel.isLoadingWorkspace();
572    }
573
574    static int getScreen() {
575        synchronized (sLock) {
576            return sScreen;
577        }
578    }
579
580    static void setScreen(int screen) {
581        synchronized (sLock) {
582            sScreen = screen;
583        }
584    }
585
586    /**
587     * Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have
588     * a configuration step, this allows the proper animations to run after other transitions.
589     */
590    private boolean completeAdd(PendingAddArguments args) {
591        boolean result = false;
592        switch (args.requestCode) {
593            case REQUEST_PICK_APPLICATION:
594                completeAddApplication(args.intent, args.container, args.screen, args.cellX,
595                        args.cellY);
596                break;
597            case REQUEST_PICK_SHORTCUT:
598                processShortcut(args.intent);
599                break;
600            case REQUEST_CREATE_SHORTCUT:
601                completeAddShortcut(args.intent, args.container, args.screen, args.cellX,
602                        args.cellY);
603                result = true;
604                break;
605            case REQUEST_CREATE_APPWIDGET:
606                int appWidgetId = args.intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
607                completeAddAppWidget(appWidgetId, args.container, args.screen, null, null);
608                result = true;
609                break;
610            case REQUEST_PICK_WALLPAPER:
611                // We just wanted the activity result here so we can clear mWaitingForResult
612                break;
613        }
614        // Before adding this resetAddInfo(), after a shortcut was added to a workspace screen,
615        // if you turned the screen off and then back while in All Apps, Launcher would not
616        // return to the workspace. Clearing mAddInfo.container here fixes this issue
617        resetAddInfo();
618        return result;
619    }
620
621    @Override
622    protected void onActivityResult(
623            final int requestCode, final int resultCode, final Intent data) {
624        if (requestCode == REQUEST_BIND_APPWIDGET) {
625            int appWidgetId = data != null ?
626                    data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
627            if (resultCode == RESULT_CANCELED) {
628                completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
629            } else if (resultCode == RESULT_OK) {
630                addAppWidgetImpl(appWidgetId, mPendingAddInfo, null, mPendingAddWidgetInfo);
631            }
632            return;
633        }
634        boolean delayExitSpringLoadedMode = false;
635        boolean isWidgetDrop = (requestCode == REQUEST_PICK_APPWIDGET ||
636                requestCode == REQUEST_CREATE_APPWIDGET);
637        mWaitingForResult = false;
638
639        // We have special handling for widgets
640        if (isWidgetDrop) {
641            int appWidgetId = data != null ?
642                    data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
643            if (appWidgetId < 0) {
644                Log.e(TAG, "Error: appWidgetId (EXTRA_APPWIDGET_ID) was not returned from the \\" +
645                        "widget configuration activity.");
646                completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
647            } else {
648                completeTwoStageWidgetDrop(resultCode, appWidgetId);
649            }
650            return;
651        }
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        if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID) {
659            final PendingAddArguments args = new PendingAddArguments();
660            args.requestCode = requestCode;
661            args.intent = data;
662            args.container = mPendingAddInfo.container;
663            args.screen = mPendingAddInfo.screen;
664            args.cellX = mPendingAddInfo.cellX;
665            args.cellY = mPendingAddInfo.cellY;
666            if (isWorkspaceLocked()) {
667                sPendingAddList.add(args);
668            } else {
669                delayExitSpringLoadedMode = completeAdd(args);
670            }
671        }
672        mDragLayer.clearAnimatedView();
673        // Exit spring loaded mode if necessary after cancelling the configuration of a widget
674        exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), delayExitSpringLoadedMode,
675                null);
676    }
677
678    private void completeTwoStageWidgetDrop(final int resultCode, final int appWidgetId) {
679        CellLayout cellLayout =
680                (CellLayout) mWorkspace.getChildAt(mPendingAddInfo.screen);
681        Runnable onCompleteRunnable = null;
682        int animationType = 0;
683
684        AppWidgetHostView boundWidget = null;
685        if (resultCode == RESULT_OK) {
686            animationType = Workspace.COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION;
687            final AppWidgetHostView layout = mAppWidgetHost.createView(this, appWidgetId,
688                    mPendingAddWidgetInfo);
689            boundWidget = layout;
690            onCompleteRunnable = new Runnable() {
691                @Override
692                public void run() {
693                    completeAddAppWidget(appWidgetId, mPendingAddInfo.container,
694                            mPendingAddInfo.screen, layout, null);
695                    exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
696                            null);
697                }
698            };
699        } else if (resultCode == RESULT_CANCELED) {
700            animationType = Workspace.CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION;
701            onCompleteRunnable = new Runnable() {
702                @Override
703                public void run() {
704                    exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
705                            null);
706                }
707            };
708        }
709        if (mDragLayer.getAnimatedView() != null) {
710            mWorkspace.animateWidgetDrop(mPendingAddInfo, cellLayout,
711                    (DragView) mDragLayer.getAnimatedView(), onCompleteRunnable,
712                    animationType, boundWidget, true);
713        } else {
714            // The animated view may be null in the case of a rotation during widget configuration
715            onCompleteRunnable.run();
716        }
717    }
718
719    @Override
720    protected void onResume() {
721        super.onResume();
722
723        // Restore the previous launcher state
724        if (mOnResumeState == State.WORKSPACE) {
725            showWorkspace(false);
726        } else if (mOnResumeState == State.APPS_CUSTOMIZE) {
727            showAllApps(false);
728        }
729        mOnResumeState = State.NONE;
730
731        // Process any items that were added while Launcher was away
732        InstallShortcutReceiver.flushInstallQueue(this);
733
734        mPaused = false;
735        sPausedFromUserAction = false;
736        if (mRestoring || mOnResumeNeedsLoad) {
737            mWorkspaceLoading = true;
738            mModel.startLoader(true, -1);
739            mRestoring = false;
740            mOnResumeNeedsLoad = false;
741        }
742
743        // Reset the pressed state of icons that were locked in the press state while activities
744        // were launching
745        if (mWaitingForResume != null) {
746            // Resets the previous workspace icon press state
747            mWaitingForResume.setStayPressed(false);
748        }
749        if (mAppsCustomizeContent != null) {
750            // Resets the previous all apps icon press state
751            mAppsCustomizeContent.resetDrawableState();
752        }
753        // It is possible that widgets can receive updates while launcher is not in the foreground.
754        // Consequently, the widgets will be inflated in the orientation of the foreground activity
755        // (framework issue). On resuming, we ensure that any widgets are inflated for the current
756        // orientation.
757        getWorkspace().reinflateWidgetsIfNecessary();
758
759        // Again, as with the above scenario, it's possible that one or more of the global icons
760        // were updated in the wrong orientation.
761        updateGlobalIcons();
762    }
763
764    @Override
765    protected void onPause() {
766        // NOTE: We want all transitions from launcher to act as if the wallpaper were enabled
767        // to be consistent.  So re-enable the flag here, and we will re-disable it as necessary
768        // when Launcher resumes and we are still in AllApps.
769        updateWallpaperVisibility(true);
770
771        super.onPause();
772        mPaused = true;
773        mDragController.cancelDrag();
774        mDragController.resetLastGestureUpTime();
775    }
776
777    @Override
778    public Object onRetainNonConfigurationInstance() {
779        // Flag the loader to stop early before switching
780        mModel.stopLoader();
781        if (mAppsCustomizeContent != null) {
782            mAppsCustomizeContent.surrender();
783        }
784        return Boolean.TRUE;
785    }
786
787    // We can't hide the IME if it was forced open.  So don't bother
788    /*
789    @Override
790    public void onWindowFocusChanged(boolean hasFocus) {
791        super.onWindowFocusChanged(hasFocus);
792
793        if (hasFocus) {
794            final InputMethodManager inputManager = (InputMethodManager)
795                    getSystemService(Context.INPUT_METHOD_SERVICE);
796            WindowManager.LayoutParams lp = getWindow().getAttributes();
797            inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new
798                        android.os.Handler()) {
799                        protected void onReceiveResult(int resultCode, Bundle resultData) {
800                            Log.d(TAG, "ResultReceiver got resultCode=" + resultCode);
801                        }
802                    });
803            Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged");
804        }
805    }
806    */
807
808    private boolean acceptFilter() {
809        final InputMethodManager inputManager = (InputMethodManager)
810                getSystemService(Context.INPUT_METHOD_SERVICE);
811        return !inputManager.isFullscreenMode();
812    }
813
814    @Override
815    public boolean onKeyDown(int keyCode, KeyEvent event) {
816        final int uniChar = event.getUnicodeChar();
817        final boolean handled = super.onKeyDown(keyCode, event);
818        final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar);
819        if (!handled && acceptFilter() && isKeyNotWhitespace) {
820            boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
821                    keyCode, event);
822            if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
823                // something usable has been typed - start a search
824                // the typed text will be retrieved and cleared by
825                // showSearchDialog()
826                // If there are multiple keystrokes before the search dialog takes focus,
827                // onSearchRequested() will be called for every keystroke,
828                // but it is idempotent, so it's fine.
829                return onSearchRequested();
830            }
831        }
832
833        // Eat the long press event so the keyboard doesn't come up.
834        if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
835            return true;
836        }
837
838        return handled;
839    }
840
841    private String getTypedText() {
842        return mDefaultKeySsb.toString();
843    }
844
845    private void clearTypedText() {
846        mDefaultKeySsb.clear();
847        mDefaultKeySsb.clearSpans();
848        Selection.setSelection(mDefaultKeySsb, 0);
849    }
850
851    /**
852     * Given the integer (ordinal) value of a State enum instance, convert it to a variable of type
853     * State
854     */
855    private static State intToState(int stateOrdinal) {
856        State state = State.WORKSPACE;
857        final State[] stateValues = State.values();
858        for (int i = 0; i < stateValues.length; i++) {
859            if (stateValues[i].ordinal() == stateOrdinal) {
860                state = stateValues[i];
861                break;
862            }
863        }
864        return state;
865    }
866
867    /**
868     * Restores the previous state, if it exists.
869     *
870     * @param savedState The previous state.
871     */
872    private void restoreState(Bundle savedState) {
873        if (savedState == null) {
874            return;
875        }
876
877        State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
878        if (state == State.APPS_CUSTOMIZE) {
879            mOnResumeState = State.APPS_CUSTOMIZE;
880        }
881
882        int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
883        if (currentScreen > -1) {
884            mWorkspace.setCurrentPage(currentScreen);
885        }
886
887        final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
888        final int pendingAddScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
889
890        if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
891            mPendingAddInfo.container = pendingAddContainer;
892            mPendingAddInfo.screen = pendingAddScreen;
893            mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
894            mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
895            mPendingAddInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
896            mPendingAddInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
897            mPendingAddWidgetInfo = savedState.getParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO);
898            mWaitingForResult = true;
899            mRestoring = true;
900        }
901
902
903        boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
904        if (renameFolder) {
905            long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
906            mFolderInfo = mModel.getFolderById(this, sFolders, id);
907            mRestoring = true;
908        }
909
910
911        // Restore the AppsCustomize tab
912        if (mAppsCustomizeTabHost != null) {
913            String curTab = savedState.getString("apps_customize_currentTab");
914            if (curTab != null) {
915                mAppsCustomizeTabHost.setContentTypeImmediate(
916                        mAppsCustomizeTabHost.getContentTypeForTabTag(curTab));
917                mAppsCustomizeContent.loadAssociatedPages(
918                        mAppsCustomizeContent.getCurrentPage());
919            }
920
921            int currentIndex = savedState.getInt("apps_customize_currentIndex");
922            mAppsCustomizeContent.restorePageForIndex(currentIndex);
923        }
924    }
925
926    /**
927     * Finds all the views we need and configure them properly.
928     */
929    private void setupViews() {
930        final DragController dragController = mDragController;
931
932        mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
933        mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
934        mQsbDivider = (ImageView) findViewById(R.id.qsb_divider);
935        mDockDivider = (ImageView) findViewById(R.id.dock_divider);
936
937        // Setup the drag layer
938        mDragLayer.setup(this, dragController);
939
940        // Setup the hotseat
941        mHotseat = (Hotseat) findViewById(R.id.hotseat);
942        if (mHotseat != null) {
943            mHotseat.setup(this);
944        }
945
946        // Setup the workspace
947        mWorkspace.setHapticFeedbackEnabled(false);
948        mWorkspace.setOnLongClickListener(this);
949        mWorkspace.setup(dragController);
950        dragController.addDragListener(mWorkspace);
951
952        // Get the search/delete bar
953        mSearchDropTargetBar = (SearchDropTargetBar) mDragLayer.findViewById(R.id.qsb_bar);
954
955        // Setup AppsCustomize
956        mAppsCustomizeTabHost = (AppsCustomizeTabHost)
957                findViewById(R.id.apps_customize_pane);
958        mAppsCustomizeContent = (AppsCustomizePagedView)
959                mAppsCustomizeTabHost.findViewById(R.id.apps_customize_pane_content);
960        mAppsCustomizeContent.setup(this, dragController);
961
962        // Setup the drag controller (drop targets have to be added in reverse order in priority)
963        dragController.setDragScoller(mWorkspace);
964        dragController.setScrollView(mDragLayer);
965        dragController.setMoveTarget(mWorkspace);
966        dragController.addDropTarget(mWorkspace);
967        if (mSearchDropTargetBar != null) {
968            mSearchDropTargetBar.setup(this, dragController);
969        }
970    }
971
972    /**
973     * Creates a view representing a shortcut.
974     *
975     * @param info The data structure describing the shortcut.
976     *
977     * @return A View inflated from R.layout.application.
978     */
979    View createShortcut(ShortcutInfo info) {
980        return createShortcut(R.layout.application,
981                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info);
982    }
983
984    /**
985     * Creates a view representing a shortcut inflated from the specified resource.
986     *
987     * @param layoutResId The id of the XML layout used to create the shortcut.
988     * @param parent The group the shortcut belongs to.
989     * @param info The data structure describing the shortcut.
990     *
991     * @return A View inflated from layoutResId.
992     */
993    View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) {
994        BubbleTextView favorite = (BubbleTextView) mInflater.inflate(layoutResId, parent, false);
995        favorite.applyFromShortcutInfo(info, mIconCache);
996        favorite.setOnClickListener(this);
997        return favorite;
998    }
999
1000    /**
1001     * Add an application shortcut to the workspace.
1002     *
1003     * @param data The intent describing the application.
1004     * @param cellInfo The position on screen where to create the shortcut.
1005     */
1006    void completeAddApplication(Intent data, long container, int screen, int cellX, int cellY) {
1007        final int[] cellXY = mTmpAddItemCellCoordinates;
1008        final CellLayout layout = getCellLayout(container, screen);
1009
1010        // First we check if we already know the exact location where we want to add this item.
1011        if (cellX >= 0 && cellY >= 0) {
1012            cellXY[0] = cellX;
1013            cellXY[1] = cellY;
1014        } else if (!layout.findCellForSpan(cellXY, 1, 1)) {
1015            showOutOfSpaceMessage(isHotseatLayout(layout));
1016            return;
1017        }
1018
1019        final ShortcutInfo info = mModel.getShortcutInfo(getPackageManager(), data, this);
1020
1021        if (info != null) {
1022            info.setActivity(data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK |
1023                    Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1024            info.container = ItemInfo.NO_ID;
1025            mWorkspace.addApplicationShortcut(info, layout, container, screen, cellXY[0], cellXY[1],
1026                    isWorkspaceLocked(), cellX, cellY);
1027        } else {
1028            Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data);
1029        }
1030    }
1031
1032    /**
1033     * Add a shortcut to the workspace.
1034     *
1035     * @param data The intent describing the shortcut.
1036     * @param cellInfo The position on screen where to create the shortcut.
1037     */
1038    private void completeAddShortcut(Intent data, long container, int screen, int cellX,
1039            int cellY) {
1040        int[] cellXY = mTmpAddItemCellCoordinates;
1041        int[] touchXY = mPendingAddInfo.dropPos;
1042        CellLayout layout = getCellLayout(container, screen);
1043
1044        boolean foundCellSpan = false;
1045
1046        ShortcutInfo info = mModel.infoFromShortcutIntent(this, data, null);
1047        if (info == null) {
1048            return;
1049        }
1050        final View view = createShortcut(info);
1051
1052        // First we check if we already know the exact location where we want to add this item.
1053        if (cellX >= 0 && cellY >= 0) {
1054            cellXY[0] = cellX;
1055            cellXY[1] = cellY;
1056            foundCellSpan = true;
1057
1058            // If appropriate, either create a folder or add to an existing folder
1059            if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0,
1060                    true, null,null)) {
1061                return;
1062            }
1063            DragObject dragObject = new DragObject();
1064            dragObject.dragInfo = info;
1065            if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject,
1066                    true)) {
1067                return;
1068            }
1069        } else if (touchXY != null) {
1070            // when dragging and dropping, just find the closest free spot
1071            int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY);
1072            foundCellSpan = (result != null);
1073        } else {
1074            foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
1075        }
1076
1077        if (!foundCellSpan) {
1078            showOutOfSpaceMessage(isHotseatLayout(layout));
1079            return;
1080        }
1081
1082        LauncherModel.addItemToDatabase(this, info, container, screen, cellXY[0], cellXY[1], false);
1083
1084        if (!mRestoring) {
1085            mWorkspace.addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1,
1086                    isWorkspaceLocked());
1087        }
1088    }
1089
1090    static int[] getSpanForWidget(Context context, ComponentName component, int minWidth,
1091            int minHeight) {
1092        Rect padding = AppWidgetHostView.getDefaultPaddingForWidget(context, component, null);
1093        // We want to account for the extra amount of padding that we are adding to the widget
1094        // to ensure that it gets the full amount of space that it has requested
1095        int requiredWidth = minWidth + padding.left + padding.right;
1096        int requiredHeight = minHeight + padding.top + padding.bottom;
1097        return CellLayout.rectToCell(context.getResources(), requiredWidth, requiredHeight, null);
1098    }
1099
1100    static int[] getSpanForWidget(Context context, AppWidgetProviderInfo info) {
1101        return getSpanForWidget(context, info.provider, info.minWidth, info.minHeight);
1102    }
1103
1104    static int[] getMinSpanForWidget(Context context, AppWidgetProviderInfo info) {
1105        return getSpanForWidget(context, info.provider, info.minResizeWidth, info.minResizeHeight);
1106    }
1107
1108    static int[] getSpanForWidget(Context context, PendingAddWidgetInfo info) {
1109        return getSpanForWidget(context, info.componentName, info.minWidth, info.minHeight);
1110    }
1111
1112    static int[] getMinSpanForWidget(Context context, PendingAddWidgetInfo info) {
1113        return getSpanForWidget(context, info.componentName, info.minResizeWidth,
1114                info.minResizeHeight);
1115    }
1116
1117    /**
1118     * Add a widget to the workspace.
1119     *
1120     * @param appWidgetId The app widget id
1121     * @param cellInfo The position on screen where to create the widget.
1122     */
1123    private void completeAddAppWidget(final int appWidgetId, long container, int screen,
1124            AppWidgetHostView hostView, AppWidgetProviderInfo appWidgetInfo) {
1125        if (appWidgetInfo == null) {
1126            appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1127        }
1128
1129        // Calculate the grid spans needed to fit this widget
1130        CellLayout layout = getCellLayout(container, screen);
1131
1132        int[] minSpanXY = getMinSpanForWidget(this, appWidgetInfo);
1133        int[] spanXY = getSpanForWidget(this, appWidgetInfo);
1134
1135        // Try finding open space on Launcher screen
1136        // We have saved the position to which the widget was dragged-- this really only matters
1137        // if we are placing widgets on a "spring-loaded" screen
1138        int[] cellXY = mTmpAddItemCellCoordinates;
1139        int[] touchXY = mPendingAddInfo.dropPos;
1140        int[] finalSpan = new int[2];
1141        boolean foundCellSpan = false;
1142        if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) {
1143            cellXY[0] = mPendingAddInfo.cellX;
1144            cellXY[1] = mPendingAddInfo.cellY;
1145            spanXY[0] = mPendingAddInfo.spanX;
1146            spanXY[1] = mPendingAddInfo.spanY;
1147            foundCellSpan = true;
1148        } else if (touchXY != null) {
1149            // when dragging and dropping, just find the closest free spot
1150            int[] result = layout.findNearestVacantArea(
1151                    touchXY[0], touchXY[1], minSpanXY[0], minSpanXY[1], spanXY[0],
1152                    spanXY[1], cellXY, finalSpan);
1153            spanXY[0] = finalSpan[0];
1154            spanXY[1] = finalSpan[1];
1155            foundCellSpan = (result != null);
1156        } else {
1157            foundCellSpan = layout.findCellForSpan(cellXY, minSpanXY[0], minSpanXY[1]);
1158        }
1159
1160        if (!foundCellSpan) {
1161            if (appWidgetId != -1) {
1162                // Deleting an app widget ID is a void call but writes to disk before returning
1163                // to the caller...
1164                new Thread("deleteAppWidgetId") {
1165                    public void run() {
1166                        mAppWidgetHost.deleteAppWidgetId(appWidgetId);
1167                    }
1168                }.start();
1169            }
1170            showOutOfSpaceMessage(isHotseatLayout(layout));
1171            return;
1172        }
1173
1174        // Build Launcher-specific widget info and save to database
1175        LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId,
1176                appWidgetInfo.provider);
1177        launcherInfo.spanX = spanXY[0];
1178        launcherInfo.spanY = spanXY[1];
1179        launcherInfo.minSpanX = mPendingAddInfo.minSpanX;
1180        launcherInfo.minSpanY = mPendingAddInfo.minSpanY;
1181
1182        LauncherModel.addItemToDatabase(this, launcherInfo,
1183                container, screen, cellXY[0], cellXY[1], false);
1184
1185        if (!mRestoring) {
1186            if (hostView == null) {
1187                // Perform actual inflation because we're live
1188                launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
1189                launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
1190            } else {
1191                // The AppWidgetHostView has already been inflated and instantiated
1192                launcherInfo.hostView = hostView;
1193            }
1194
1195            launcherInfo.hostView.setTag(launcherInfo);
1196            launcherInfo.hostView.setVisibility(View.VISIBLE);
1197            launcherInfo.notifyWidgetSizeChanged(this);
1198
1199            mWorkspace.addInScreen(launcherInfo.hostView, container, screen, cellXY[0], cellXY[1],
1200                    launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
1201
1202            addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
1203        }
1204        resetAddInfo();
1205    }
1206
1207    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1208        @Override
1209        public void onReceive(Context context, Intent intent) {
1210            final String action = intent.getAction();
1211            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
1212                mUserPresent = false;
1213                mDragLayer.clearAllResizeFrames();
1214                updateRunning();
1215
1216                // Reset AllApps to its initial state only if we are not in the middle of
1217                // processing a multi-step drop
1218                if (mAppsCustomizeTabHost != null && mPendingAddInfo.container == ItemInfo.NO_ID) {
1219                    mAppsCustomizeTabHost.reset();
1220                    showWorkspace(false);
1221                }
1222            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
1223                mUserPresent = true;
1224                updateRunning();
1225            }
1226        }
1227    };
1228
1229    @Override
1230    public void onAttachedToWindow() {
1231        super.onAttachedToWindow();
1232
1233        // Listen for broadcasts related to user-presence
1234        final IntentFilter filter = new IntentFilter();
1235        filter.addAction(Intent.ACTION_SCREEN_OFF);
1236        filter.addAction(Intent.ACTION_USER_PRESENT);
1237        registerReceiver(mReceiver, filter);
1238
1239        mAttached = true;
1240        mVisible = true;
1241    }
1242
1243    @Override
1244    public void onDetachedFromWindow() {
1245        super.onDetachedFromWindow();
1246        mVisible = false;
1247
1248        if (mAttached) {
1249            unregisterReceiver(mReceiver);
1250            mAttached = false;
1251        }
1252        updateRunning();
1253    }
1254
1255    public void onWindowVisibilityChanged(int visibility) {
1256        mVisible = visibility == View.VISIBLE;
1257        updateRunning();
1258        // The following code used to be in onResume, but it turns out onResume is called when
1259        // you're in All Apps and click home to go to the workspace. onWindowVisibilityChanged
1260        // is a more appropriate event to handle
1261        if (mVisible) {
1262            mAppsCustomizeTabHost.onWindowVisible();
1263            if (!mWorkspaceLoading) {
1264                final ViewTreeObserver observer = mWorkspace.getViewTreeObserver();
1265                // We want to let Launcher draw itself at least once before we force it to build
1266                // layers on all the workspace pages, so that transitioning to Launcher from other
1267                // apps is nice and speedy. Usually the first call to preDraw doesn't correspond to
1268                // a true draw so we wait until the second preDraw call to be safe
1269                observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
1270                    public boolean onPreDraw() {
1271                        // We delay the layer building a bit in order to give
1272                        // other message processing a time to run.  In particular
1273                        // this avoids a delay in hiding the IME if it was
1274                        // currently shown, because doing that may involve
1275                        // some communication back with the app.
1276                        mWorkspace.postDelayed(mBuildLayersRunnable, 500);
1277
1278                        observer.removeOnPreDrawListener(this);
1279                        return true;
1280                    }
1281                });
1282            }
1283            // When Launcher comes back to foreground, a different Activity might be responsible for
1284            // the app market intent, so refresh the icon
1285            updateAppMarketIcon();
1286            clearTypedText();
1287        }
1288    }
1289
1290    private void sendAdvanceMessage(long delay) {
1291        mHandler.removeMessages(ADVANCE_MSG);
1292        Message msg = mHandler.obtainMessage(ADVANCE_MSG);
1293        mHandler.sendMessageDelayed(msg, delay);
1294        mAutoAdvanceSentTime = System.currentTimeMillis();
1295    }
1296
1297    private void updateRunning() {
1298        boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
1299        if (autoAdvanceRunning != mAutoAdvanceRunning) {
1300            mAutoAdvanceRunning = autoAdvanceRunning;
1301            if (autoAdvanceRunning) {
1302                long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
1303                sendAdvanceMessage(delay);
1304            } else {
1305                if (!mWidgetsToAdvance.isEmpty()) {
1306                    mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
1307                            (System.currentTimeMillis() - mAutoAdvanceSentTime));
1308                }
1309                mHandler.removeMessages(ADVANCE_MSG);
1310                mHandler.removeMessages(0); // Remove messages sent using postDelayed()
1311            }
1312        }
1313    }
1314
1315    private final Handler mHandler = new Handler() {
1316        @Override
1317        public void handleMessage(Message msg) {
1318            if (msg.what == ADVANCE_MSG) {
1319                int i = 0;
1320                for (View key: mWidgetsToAdvance.keySet()) {
1321                    final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
1322                    final int delay = mAdvanceStagger * i;
1323                    if (v instanceof Advanceable) {
1324                       postDelayed(new Runnable() {
1325                           public void run() {
1326                               ((Advanceable) v).advance();
1327                           }
1328                       }, delay);
1329                    }
1330                    i++;
1331                }
1332                sendAdvanceMessage(mAdvanceInterval);
1333            }
1334        }
1335    };
1336
1337    void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
1338        if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
1339        View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
1340        if (v instanceof Advanceable) {
1341            mWidgetsToAdvance.put(hostView, appWidgetInfo);
1342            ((Advanceable) v).fyiWillBeAdvancedByHostKThx();
1343            updateRunning();
1344        }
1345    }
1346
1347    void removeWidgetToAutoAdvance(View hostView) {
1348        if (mWidgetsToAdvance.containsKey(hostView)) {
1349            mWidgetsToAdvance.remove(hostView);
1350            updateRunning();
1351        }
1352    }
1353
1354    public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
1355        removeWidgetToAutoAdvance(launcherInfo.hostView);
1356        launcherInfo.hostView = null;
1357    }
1358
1359    void showOutOfSpaceMessage(boolean isHotseatLayout) {
1360        int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space);
1361        Toast.makeText(this, getString(strId), Toast.LENGTH_SHORT).show();
1362    }
1363
1364    public LauncherAppWidgetHost getAppWidgetHost() {
1365        return mAppWidgetHost;
1366    }
1367
1368    public LauncherModel getModel() {
1369        return mModel;
1370    }
1371
1372    void closeSystemDialogs() {
1373        getWindow().closeAllPanels();
1374
1375        // Whatever we were doing is hereby canceled.
1376        mWaitingForResult = false;
1377    }
1378
1379    @Override
1380    protected void onNewIntent(Intent intent) {
1381        super.onNewIntent(intent);
1382
1383        // Close the menu
1384        if (Intent.ACTION_MAIN.equals(intent.getAction())) {
1385            // also will cancel mWaitingForResult.
1386            closeSystemDialogs();
1387
1388            boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
1389                        != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
1390
1391            Folder openFolder = mWorkspace.getOpenFolder();
1392            // In all these cases, only animate if we're already on home
1393            mWorkspace.exitWidgetResizeMode();
1394            if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive() &&
1395                    openFolder == null) {
1396                mWorkspace.moveToDefaultScreen(true);
1397            }
1398
1399            closeFolder();
1400            exitSpringLoadedDragMode();
1401
1402            // If we are already on home, then just animate back to the workspace, otherwise, just
1403            // wait until onResume to set the state back to Workspace
1404            if (alreadyOnHome) {
1405                showWorkspace(true);
1406            } else {
1407                mOnResumeState = State.WORKSPACE;
1408            }
1409
1410            final View v = getWindow().peekDecorView();
1411            if (v != null && v.getWindowToken() != null) {
1412                InputMethodManager imm = (InputMethodManager)getSystemService(
1413                        INPUT_METHOD_SERVICE);
1414                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
1415            }
1416
1417            // Reset AllApps to its initial state
1418            if (!alreadyOnHome && mAppsCustomizeTabHost != null) {
1419                mAppsCustomizeTabHost.reset();
1420            }
1421        }
1422    }
1423
1424    @Override
1425    public void onRestoreInstanceState(Bundle state) {
1426        super.onRestoreInstanceState(state);
1427        for (int page: mSynchronouslyBoundPages) {
1428            mWorkspace.restoreInstanceStateForChild(page);
1429        }
1430    }
1431
1432    @Override
1433    protected void onSaveInstanceState(Bundle outState) {
1434        outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getNextPage());
1435        super.onSaveInstanceState(outState);
1436
1437        outState.putInt(RUNTIME_STATE, mState.ordinal());
1438        // We close any open folder since it will not be re-opened, and we need to make sure
1439        // this state is reflected.
1440        closeFolder();
1441
1442        if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screen > -1 &&
1443                mWaitingForResult) {
1444            outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
1445            outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screen);
1446            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
1447            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
1448            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, mPendingAddInfo.spanX);
1449            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, mPendingAddInfo.spanY);
1450            outState.putParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO, mPendingAddWidgetInfo);
1451        }
1452
1453        if (mFolderInfo != null && mWaitingForResult) {
1454            outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
1455            outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
1456        }
1457
1458        // Save the current AppsCustomize tab
1459        if (mAppsCustomizeTabHost != null) {
1460            String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag();
1461            if (currentTabTag != null) {
1462                outState.putString("apps_customize_currentTab", currentTabTag);
1463            }
1464            int currentIndex = mAppsCustomizeContent.getSaveInstanceStateIndex();
1465            outState.putInt("apps_customize_currentIndex", currentIndex);
1466        }
1467    }
1468
1469    @Override
1470    public void onDestroy() {
1471        super.onDestroy();
1472
1473        // Remove all pending runnables
1474        mHandler.removeMessages(ADVANCE_MSG);
1475        mHandler.removeMessages(0);
1476        mWorkspace.removeCallbacks(mBuildLayersRunnable);
1477
1478        // Stop callbacks from LauncherModel
1479        LauncherApplication app = ((LauncherApplication) getApplication());
1480        mModel.stopLoader();
1481        app.setLauncher(null);
1482
1483        try {
1484            mAppWidgetHost.stopListening();
1485        } catch (NullPointerException ex) {
1486            Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
1487        }
1488        mAppWidgetHost = null;
1489
1490        mWidgetsToAdvance.clear();
1491
1492        TextKeyListener.getInstance().release();
1493
1494        // Disconnect any of the callbacks and drawables associated with ItemInfos on the workspace
1495        // to prevent leaking Launcher activities on orientation change.
1496        if (mModel != null) {
1497            mModel.unbindItemInfosAndClearQueuedBindRunnables();
1498        }
1499
1500        getContentResolver().unregisterContentObserver(mWidgetObserver);
1501        unregisterReceiver(mCloseSystemDialogsReceiver);
1502
1503        mDragLayer.clearAllResizeFrames();
1504        ((ViewGroup) mWorkspace.getParent()).removeAllViews();
1505        mWorkspace.removeAllViews();
1506        mWorkspace = null;
1507        mDragController = null;
1508
1509        LauncherAnimUtils.onDestroyActivity();
1510    }
1511
1512    public DragController getDragController() {
1513        return mDragController;
1514    }
1515
1516    @Override
1517    public void startActivityForResult(Intent intent, int requestCode) {
1518        if (requestCode >= 0) mWaitingForResult = true;
1519        super.startActivityForResult(intent, requestCode);
1520    }
1521
1522    /**
1523     * Indicates that we want global search for this activity by setting the globalSearch
1524     * argument for {@link #startSearch} to true.
1525     */
1526    @Override
1527    public void startSearch(String initialQuery, boolean selectInitialQuery,
1528            Bundle appSearchData, boolean globalSearch) {
1529
1530        showWorkspace(true);
1531
1532        if (initialQuery == null) {
1533            // Use any text typed in the launcher as the initial query
1534            initialQuery = getTypedText();
1535        }
1536        if (appSearchData == null) {
1537            appSearchData = new Bundle();
1538            appSearchData.putString(Search.SOURCE, "launcher-search");
1539        }
1540        Rect sourceBounds = new Rect();
1541        if (mSearchDropTargetBar != null) {
1542            sourceBounds = mSearchDropTargetBar.getSearchBarBounds();
1543        }
1544
1545        startGlobalSearch(initialQuery, selectInitialQuery,
1546            appSearchData, sourceBounds);
1547    }
1548
1549    /**
1550     * Starts the global search activity. This code is a copied from SearchManager
1551     */
1552    public void startGlobalSearch(String initialQuery,
1553            boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
1554        final SearchManager searchManager =
1555            (SearchManager) getSystemService(Context.SEARCH_SERVICE);
1556        ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
1557        if (globalSearchActivity == null) {
1558            Log.w(TAG, "No global search activity found.");
1559            return;
1560        }
1561        Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
1562        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1563        intent.setComponent(globalSearchActivity);
1564        // Make sure that we have a Bundle to put source in
1565        if (appSearchData == null) {
1566            appSearchData = new Bundle();
1567        } else {
1568            appSearchData = new Bundle(appSearchData);
1569        }
1570        // Set source to package name of app that starts global search, if not set already.
1571        if (!appSearchData.containsKey("source")) {
1572            appSearchData.putString("source", getPackageName());
1573        }
1574        intent.putExtra(SearchManager.APP_DATA, appSearchData);
1575        if (!TextUtils.isEmpty(initialQuery)) {
1576            intent.putExtra(SearchManager.QUERY, initialQuery);
1577        }
1578        if (selectInitialQuery) {
1579            intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery);
1580        }
1581        intent.setSourceBounds(sourceBounds);
1582        try {
1583            startActivity(intent);
1584        } catch (ActivityNotFoundException ex) {
1585            Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
1586        }
1587    }
1588
1589    @Override
1590    public boolean onCreateOptionsMenu(Menu menu) {
1591        if (isWorkspaceLocked()) {
1592            return false;
1593        }
1594
1595        super.onCreateOptionsMenu(menu);
1596
1597        Intent manageApps = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
1598        manageApps.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1599                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1600        Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
1601        settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1602                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1603        String helpUrl = getString(R.string.help_url);
1604        Intent help = new Intent(Intent.ACTION_VIEW, Uri.parse(helpUrl));
1605        help.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1606                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1607
1608        menu.add(MENU_GROUP_WALLPAPER, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
1609            .setIcon(android.R.drawable.ic_menu_gallery)
1610            .setAlphabeticShortcut('W');
1611        menu.add(0, MENU_MANAGE_APPS, 0, R.string.menu_manage_apps)
1612            .setIcon(android.R.drawable.ic_menu_manage)
1613            .setIntent(manageApps)
1614            .setAlphabeticShortcut('M');
1615        menu.add(0, MENU_SYSTEM_SETTINGS, 0, R.string.menu_settings)
1616            .setIcon(android.R.drawable.ic_menu_preferences)
1617            .setIntent(settings)
1618            .setAlphabeticShortcut('P');
1619        if (!helpUrl.isEmpty()) {
1620            menu.add(0, MENU_HELP, 0, R.string.menu_help)
1621                .setIcon(android.R.drawable.ic_menu_help)
1622                .setIntent(help)
1623                .setAlphabeticShortcut('H');
1624        }
1625        return true;
1626    }
1627
1628    @Override
1629    public boolean onPrepareOptionsMenu(Menu menu) {
1630        super.onPrepareOptionsMenu(menu);
1631
1632        if (mAppsCustomizeTabHost.isTransitioning()) {
1633            return false;
1634        }
1635        boolean allAppsVisible = (mAppsCustomizeTabHost.getVisibility() == View.VISIBLE);
1636        menu.setGroupVisible(MENU_GROUP_WALLPAPER, !allAppsVisible);
1637
1638        return true;
1639    }
1640
1641    @Override
1642    public boolean onOptionsItemSelected(MenuItem item) {
1643        switch (item.getItemId()) {
1644        case MENU_WALLPAPER_SETTINGS:
1645            startWallpaper();
1646            return true;
1647        }
1648
1649        return super.onOptionsItemSelected(item);
1650    }
1651
1652    @Override
1653    public boolean onSearchRequested() {
1654        startSearch(null, false, null, true);
1655        // Use a custom animation for launching search
1656        return true;
1657    }
1658
1659    public boolean isWorkspaceLocked() {
1660        return mWorkspaceLoading || mWaitingForResult;
1661    }
1662
1663    private void resetAddInfo() {
1664        mPendingAddInfo.container = ItemInfo.NO_ID;
1665        mPendingAddInfo.screen = -1;
1666        mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1;
1667        mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1;
1668        mPendingAddInfo.minSpanX = mPendingAddInfo.minSpanY = -1;
1669        mPendingAddInfo.dropPos = null;
1670    }
1671
1672    void addAppWidgetImpl(final int appWidgetId, ItemInfo info, AppWidgetHostView boundWidget,
1673            AppWidgetProviderInfo appWidgetInfo) {
1674        if (appWidgetInfo.configure != null) {
1675            mPendingAddWidgetInfo = appWidgetInfo;
1676
1677            // Launch over to configure widget, if needed
1678            Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
1679            intent.setComponent(appWidgetInfo.configure);
1680            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1681            startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET);
1682        } else {
1683            // Otherwise just add it
1684            completeAddAppWidget(appWidgetId, info.container, info.screen, boundWidget,
1685                    appWidgetInfo);
1686            // Exit spring loaded mode if necessary after adding the widget
1687            exitSpringLoadedDragModeDelayed(true, false, null);
1688        }
1689    }
1690
1691    /**
1692     * Process a shortcut drop.
1693     *
1694     * @param componentName The name of the component
1695     * @param screen The screen where it should be added
1696     * @param cell The cell it should be added to, optional
1697     * @param position The location on the screen where it was dropped, optional
1698     */
1699    void processShortcutFromDrop(ComponentName componentName, long container, int screen,
1700            int[] cell, int[] loc) {
1701        resetAddInfo();
1702        mPendingAddInfo.container = container;
1703        mPendingAddInfo.screen = screen;
1704        mPendingAddInfo.dropPos = loc;
1705
1706        if (cell != null) {
1707            mPendingAddInfo.cellX = cell[0];
1708            mPendingAddInfo.cellY = cell[1];
1709        }
1710
1711        Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
1712        createShortcutIntent.setComponent(componentName);
1713        processShortcut(createShortcutIntent);
1714    }
1715
1716    /**
1717     * Process a widget drop.
1718     *
1719     * @param info The PendingAppWidgetInfo of the widget being added.
1720     * @param screen The screen where it should be added
1721     * @param cell The cell it should be added to, optional
1722     * @param position The location on the screen where it was dropped, optional
1723     */
1724    void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, int screen,
1725            int[] cell, int[] span, int[] loc) {
1726        resetAddInfo();
1727        mPendingAddInfo.container = info.container = container;
1728        mPendingAddInfo.screen = info.screen = screen;
1729        mPendingAddInfo.dropPos = loc;
1730        mPendingAddInfo.minSpanX = info.minSpanX;
1731        mPendingAddInfo.minSpanY = info.minSpanY;
1732
1733        if (cell != null) {
1734            mPendingAddInfo.cellX = cell[0];
1735            mPendingAddInfo.cellY = cell[1];
1736        }
1737        if (span != null) {
1738            mPendingAddInfo.spanX = span[0];
1739            mPendingAddInfo.spanY = span[1];
1740        }
1741
1742        AppWidgetHostView hostView = info.boundWidget;
1743        int appWidgetId;
1744        if (hostView != null) {
1745            appWidgetId = hostView.getAppWidgetId();
1746            addAppWidgetImpl(appWidgetId, info, hostView, info.info);
1747        } else {
1748            // In this case, we either need to start an activity to get permission to bind
1749            // the widget, or we need to start an activity to configure the widget, or both.
1750            appWidgetId = getAppWidgetHost().allocateAppWidgetId();
1751            Bundle options = info.bindOptions;
1752
1753            boolean success = false;
1754            if (options != null) {
1755                success = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
1756                        info.componentName, options);
1757            } else {
1758                success = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
1759                        info.componentName);
1760            }
1761            if (success) {
1762                addAppWidgetImpl(appWidgetId, info, null, info.info);
1763            } else {
1764                mPendingAddWidgetInfo = info.info;
1765                Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
1766                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1767                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.componentName);
1768                // TODO: we need to make sure that this accounts for the options bundle.
1769                // intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, options);
1770                startActivityForResult(intent, REQUEST_BIND_APPWIDGET);
1771            }
1772        }
1773    }
1774
1775    void processShortcut(Intent intent) {
1776        // Handle case where user selected "Applications"
1777        String applicationName = getResources().getString(R.string.group_applications);
1778        String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1779
1780        if (applicationName != null && applicationName.equals(shortcutName)) {
1781            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1782            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1783
1784            Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1785            pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1786            pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application));
1787            startActivityForResultSafely(pickIntent, REQUEST_PICK_APPLICATION);
1788        } else {
1789            startActivityForResultSafely(intent, REQUEST_CREATE_SHORTCUT);
1790        }
1791    }
1792
1793    void processWallpaper(Intent intent) {
1794        startActivityForResult(intent, REQUEST_PICK_WALLPAPER);
1795    }
1796
1797    FolderIcon addFolder(CellLayout layout, long container, final int screen, int cellX,
1798            int cellY) {
1799        final FolderInfo folderInfo = new FolderInfo();
1800        folderInfo.title = getText(R.string.folder_name);
1801
1802        // Update the model
1803        LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screen, cellX, cellY,
1804                false);
1805        sFolders.put(folderInfo.id, folderInfo);
1806
1807        // Create the view
1808        FolderIcon newFolder =
1809            FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache);
1810        mWorkspace.addInScreen(newFolder, container, screen, cellX, cellY, 1, 1,
1811                isWorkspaceLocked());
1812        return newFolder;
1813    }
1814
1815    void removeFolder(FolderInfo folder) {
1816        sFolders.remove(folder.id);
1817    }
1818
1819    private void startWallpaper() {
1820        showWorkspace(true);
1821        final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1822        Intent chooser = Intent.createChooser(pickWallpaper,
1823                getText(R.string.chooser_wallpaper));
1824        // NOTE: Adds a configure option to the chooser if the wallpaper supports it
1825        //       Removed in Eclair MR1
1826//        WallpaperManager wm = (WallpaperManager)
1827//                getSystemService(Context.WALLPAPER_SERVICE);
1828//        WallpaperInfo wi = wm.getWallpaperInfo();
1829//        if (wi != null && wi.getSettingsActivity() != null) {
1830//            LabeledIntent li = new LabeledIntent(getPackageName(),
1831//                    R.string.configure_wallpaper, 0);
1832//            li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
1833//            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
1834//        }
1835        startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
1836    }
1837
1838    /**
1839     * Registers various content observers. The current implementation registers
1840     * only a favorites observer to keep track of the favorites applications.
1841     */
1842    private void registerContentObservers() {
1843        ContentResolver resolver = getContentResolver();
1844        resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
1845                true, mWidgetObserver);
1846    }
1847
1848    @Override
1849    public boolean dispatchKeyEvent(KeyEvent event) {
1850        if (event.getAction() == KeyEvent.ACTION_DOWN) {
1851            switch (event.getKeyCode()) {
1852                case KeyEvent.KEYCODE_HOME:
1853                    return true;
1854                case KeyEvent.KEYCODE_VOLUME_DOWN:
1855                    if (doesFileExist(DUMP_STATE_PROPERTY)) {
1856                        dumpState();
1857                        return true;
1858                    }
1859                    break;
1860            }
1861        } else if (event.getAction() == KeyEvent.ACTION_UP) {
1862            switch (event.getKeyCode()) {
1863                case KeyEvent.KEYCODE_HOME:
1864                    return true;
1865            }
1866        }
1867
1868        return super.dispatchKeyEvent(event);
1869    }
1870
1871    @Override
1872    public void onBackPressed() {
1873        if (isAllAppsVisible()) {
1874            showWorkspace(true);
1875        } else if (mWorkspace.getOpenFolder() != null) {
1876            Folder openFolder = mWorkspace.getOpenFolder();
1877            if (openFolder.isEditingName()) {
1878                openFolder.dismissEditingName();
1879            } else {
1880                closeFolder();
1881            }
1882        } else {
1883            mWorkspace.exitWidgetResizeMode();
1884
1885            // Back button is a no-op here, but give at least some feedback for the button press
1886            mWorkspace.showOutlinesTemporarily();
1887        }
1888    }
1889
1890    /**
1891     * Re-listen when widgets are reset.
1892     */
1893    private void onAppWidgetReset() {
1894        if (mAppWidgetHost != null) {
1895            mAppWidgetHost.startListening();
1896        }
1897    }
1898
1899    /**
1900     * Launches the intent referred by the clicked shortcut.
1901     *
1902     * @param v The view representing the clicked shortcut.
1903     */
1904    public void onClick(View v) {
1905        // Make sure that rogue clicks don't get through while allapps is launching, or after the
1906        // view has detached (it's possible for this to happen if the view is removed mid touch).
1907        if (v.getWindowToken() == null) {
1908            return;
1909        }
1910
1911        if (!mWorkspace.isFinishedSwitchingState()) {
1912            return;
1913        }
1914
1915        Object tag = v.getTag();
1916        if (tag instanceof ShortcutInfo) {
1917            // Open shortcut
1918            final Intent intent = ((ShortcutInfo) tag).intent;
1919            int[] pos = new int[2];
1920            v.getLocationOnScreen(pos);
1921            intent.setSourceBounds(new Rect(pos[0], pos[1],
1922                    pos[0] + v.getWidth(), pos[1] + v.getHeight()));
1923
1924            boolean success = startActivitySafely(v, intent, tag);
1925
1926            if (success && v instanceof BubbleTextView) {
1927                mWaitingForResume = (BubbleTextView) v;
1928                mWaitingForResume.setStayPressed(true);
1929            }
1930        } else if (tag instanceof FolderInfo) {
1931            if (v instanceof FolderIcon) {
1932                FolderIcon fi = (FolderIcon) v;
1933                handleFolderClick(fi);
1934            }
1935        } else if (v == mAllAppsButton) {
1936            if (isAllAppsVisible()) {
1937                showWorkspace(true);
1938            } else {
1939                onClickAllAppsButton(v);
1940            }
1941        }
1942    }
1943
1944    public boolean onTouch(View v, MotionEvent event) {
1945        // this is an intercepted event being forwarded from mWorkspace;
1946        // clicking anywhere on the workspace causes the customization drawer to slide down
1947        showWorkspace(true);
1948        return false;
1949    }
1950
1951    /**
1952     * Event handler for the search button
1953     *
1954     * @param v The view that was clicked.
1955     */
1956    public void onClickSearchButton(View v) {
1957        v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
1958
1959        onSearchRequested();
1960    }
1961
1962    /**
1963     * Event handler for the voice button
1964     *
1965     * @param v The view that was clicked.
1966     */
1967    public void onClickVoiceButton(View v) {
1968        v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
1969
1970        try {
1971            final SearchManager searchManager =
1972                    (SearchManager) getSystemService(Context.SEARCH_SERVICE);
1973            ComponentName activityName = searchManager.getGlobalSearchActivity();
1974            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1975            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1976            if (activityName != null) {
1977                intent.setPackage(activityName.getPackageName());
1978            }
1979            startActivity(null, intent, "onClickVoiceButton");
1980        } catch (ActivityNotFoundException e) {
1981            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1982            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1983            startActivitySafely(null, intent, "onClickVoiceButton");
1984        }
1985    }
1986
1987    /**
1988     * Event handler for the "grid" button that appears on the home screen, which
1989     * enters all apps mode.
1990     *
1991     * @param v The view that was clicked.
1992     */
1993    public void onClickAllAppsButton(View v) {
1994        showAllApps(true);
1995    }
1996
1997    public void onTouchDownAllAppsButton(View v) {
1998        // Provide the same haptic feedback that the system offers for virtual keys.
1999        v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
2000    }
2001
2002    public void onClickAppMarketButton(View v) {
2003        if (mAppMarketIntent != null) {
2004            startActivitySafely(v, mAppMarketIntent, "app market");
2005        } else {
2006            Log.e(TAG, "Invalid app market intent.");
2007        }
2008    }
2009
2010    void startApplicationDetailsActivity(ComponentName componentName) {
2011        String packageName = componentName.getPackageName();
2012        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
2013                Uri.fromParts("package", packageName, null));
2014        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
2015        startActivitySafely(null, intent, "startApplicationDetailsActivity");
2016    }
2017
2018    void startApplicationUninstallActivity(ApplicationInfo appInfo) {
2019        if ((appInfo.flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) {
2020            // System applications cannot be installed. For now, show a toast explaining that.
2021            // We may give them the option of disabling apps this way.
2022            int messageId = R.string.uninstall_system_app_text;
2023            Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
2024        } else {
2025            String packageName = appInfo.componentName.getPackageName();
2026            String className = appInfo.componentName.getClassName();
2027            Intent intent = new Intent(
2028                    Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
2029            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
2030                    Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
2031            startActivity(intent);
2032        }
2033    }
2034
2035    boolean startActivity(View v, Intent intent, Object tag) {
2036        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2037
2038        try {
2039            // Only launch using the new animation if the shortcut has not opted out (this is a
2040            // private contract between launcher and may be ignored in the future).
2041            boolean useLaunchAnimation = (v != null) &&
2042                    !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
2043            if (useLaunchAnimation) {
2044                ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
2045                        v.getMeasuredWidth(), v.getMeasuredHeight());
2046
2047                startActivity(intent, opts.toBundle());
2048            } else {
2049                startActivity(intent);
2050            }
2051            return true;
2052        } catch (SecurityException e) {
2053            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2054            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
2055                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
2056                    "or use the exported attribute for this activity. "
2057                    + "tag="+ tag + " intent=" + intent, e);
2058        }
2059        return false;
2060    }
2061
2062    boolean startActivitySafely(View v, Intent intent, Object tag) {
2063        boolean success = false;
2064        try {
2065            success = startActivity(v, intent, tag);
2066        } catch (ActivityNotFoundException e) {
2067            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2068            Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
2069        }
2070        return success;
2071    }
2072
2073    void startActivityForResultSafely(Intent intent, int requestCode) {
2074        try {
2075            startActivityForResult(intent, requestCode);
2076        } catch (ActivityNotFoundException e) {
2077            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2078        } catch (SecurityException e) {
2079            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2080            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
2081                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
2082                    "or use the exported attribute for this activity.", e);
2083        }
2084    }
2085
2086    private void handleFolderClick(FolderIcon folderIcon) {
2087        final FolderInfo info = folderIcon.getFolderInfo();
2088        Folder openFolder = mWorkspace.getFolderForTag(info);
2089
2090        // If the folder info reports that the associated folder is open, then verify that
2091        // it is actually opened. There have been a few instances where this gets out of sync.
2092        if (info.opened && openFolder == null) {
2093            Log.d(TAG, "Folder info marked as open, but associated folder is not open. Screen: "
2094                    + info.screen + " (" + info.cellX + ", " + info.cellY + ")");
2095            info.opened = false;
2096        }
2097
2098        if (!info.opened && !folderIcon.getFolder().isDestroyed()) {
2099            // Close any open folder
2100            closeFolder();
2101            // Open the requested folder
2102            openFolder(folderIcon);
2103        } else {
2104            // Find the open folder...
2105            int folderScreen;
2106            if (openFolder != null) {
2107                folderScreen = mWorkspace.getPageForView(openFolder);
2108                // .. and close it
2109                closeFolder(openFolder);
2110                if (folderScreen != mWorkspace.getCurrentPage()) {
2111                    // Close any folder open on the current screen
2112                    closeFolder();
2113                    // Pull the folder onto this screen
2114                    openFolder(folderIcon);
2115                }
2116            }
2117        }
2118    }
2119
2120    /**
2121     * This method draws the FolderIcon to an ImageView and then adds and positions that ImageView
2122     * in the DragLayer in the exact absolute location of the original FolderIcon.
2123     */
2124    private void copyFolderIconToImage(FolderIcon fi) {
2125        final int width = fi.getMeasuredWidth();
2126        final int height = fi.getMeasuredHeight();
2127
2128        // Lazy load ImageView, Bitmap and Canvas
2129        if (mFolderIconImageView == null) {
2130            mFolderIconImageView = new ImageView(this);
2131        }
2132        if (mFolderIconBitmap == null || mFolderIconBitmap.getWidth() != width ||
2133                mFolderIconBitmap.getHeight() != height) {
2134            mFolderIconBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
2135            mFolderIconCanvas = new Canvas(mFolderIconBitmap);
2136        }
2137
2138        DragLayer.LayoutParams lp;
2139        if (mFolderIconImageView.getLayoutParams() instanceof DragLayer.LayoutParams) {
2140            lp = (DragLayer.LayoutParams) mFolderIconImageView.getLayoutParams();
2141        } else {
2142            lp = new DragLayer.LayoutParams(width, height);
2143        }
2144
2145        // The layout from which the folder is being opened may be scaled, adjust the starting
2146        // view size by this scale factor.
2147        float scale = mDragLayer.getDescendantRectRelativeToSelf(fi, mRectForFolderAnimation);
2148        lp.customPosition = true;
2149        lp.x = mRectForFolderAnimation.left;
2150        lp.y = mRectForFolderAnimation.top;
2151        lp.width = (int) (scale * width);
2152        lp.height = (int) (scale * height);
2153
2154        mFolderIconCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
2155        fi.draw(mFolderIconCanvas);
2156        mFolderIconImageView.setImageBitmap(mFolderIconBitmap);
2157        if (fi.getFolder() != null) {
2158            mFolderIconImageView.setPivotX(fi.getFolder().getPivotXForIconAnimation());
2159            mFolderIconImageView.setPivotY(fi.getFolder().getPivotYForIconAnimation());
2160        }
2161        // Just in case this image view is still in the drag layer from a previous animation,
2162        // we remove it and re-add it.
2163        if (mDragLayer.indexOfChild(mFolderIconImageView) != -1) {
2164            mDragLayer.removeView(mFolderIconImageView);
2165        }
2166        mDragLayer.addView(mFolderIconImageView, lp);
2167        if (fi.getFolder() != null) {
2168            fi.getFolder().bringToFront();
2169        }
2170    }
2171
2172    private void growAndFadeOutFolderIcon(FolderIcon fi) {
2173        if (fi == null) return;
2174        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
2175        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
2176        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
2177
2178        FolderInfo info = (FolderInfo) fi.getTag();
2179        if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2180            CellLayout cl = (CellLayout) fi.getParent().getParent();
2181            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams();
2182            cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY);
2183        }
2184
2185        // Push an ImageView copy of the FolderIcon into the DragLayer and hide the original
2186        copyFolderIconToImage(fi);
2187        fi.setVisibility(View.INVISIBLE);
2188
2189        ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
2190                scaleX, scaleY);
2191        oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
2192        oa.start();
2193    }
2194
2195    private void shrinkAndFadeInFolderIcon(final FolderIcon fi) {
2196        if (fi == null) return;
2197        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
2198        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
2199        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
2200
2201        final CellLayout cl = (CellLayout) fi.getParent().getParent();
2202
2203        // We remove and re-draw the FolderIcon in-case it has changed
2204        mDragLayer.removeView(mFolderIconImageView);
2205        copyFolderIconToImage(fi);
2206        ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
2207                scaleX, scaleY);
2208        oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
2209        oa.addListener(new AnimatorListenerAdapter() {
2210            @Override
2211            public void onAnimationEnd(Animator animation) {
2212                if (cl != null) {
2213                    cl.clearFolderLeaveBehind();
2214                    // Remove the ImageView copy of the FolderIcon and make the original visible.
2215                    mDragLayer.removeView(mFolderIconImageView);
2216                    fi.setVisibility(View.VISIBLE);
2217                }
2218            }
2219        });
2220        oa.start();
2221    }
2222
2223    /**
2224     * Opens the user folder described by the specified tag. The opening of the folder
2225     * is animated relative to the specified View. If the View is null, no animation
2226     * is played.
2227     *
2228     * @param folderInfo The FolderInfo describing the folder to open.
2229     */
2230    public void openFolder(FolderIcon folderIcon) {
2231        Folder folder = folderIcon.getFolder();
2232        FolderInfo info = folder.mInfo;
2233
2234        info.opened = true;
2235
2236        // Just verify that the folder hasn't already been added to the DragLayer.
2237        // There was a one-off crash where the folder had a parent already.
2238        if (folder.getParent() == null) {
2239            mDragLayer.addView(folder);
2240            mDragController.addDropTarget((DropTarget) folder);
2241        } else {
2242            Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" +
2243                    folder.getParent() + ").");
2244        }
2245        folder.animateOpen();
2246        growAndFadeOutFolderIcon(folderIcon);
2247    }
2248
2249    public void closeFolder() {
2250        Folder folder = mWorkspace.getOpenFolder();
2251        if (folder != null) {
2252            if (folder.isEditingName()) {
2253                folder.dismissEditingName();
2254            }
2255            closeFolder(folder);
2256
2257            // Dismiss the folder cling
2258            dismissFolderCling(null);
2259        }
2260    }
2261
2262    void closeFolder(Folder folder) {
2263        folder.getInfo().opened = false;
2264
2265        ViewGroup parent = (ViewGroup) folder.getParent().getParent();
2266        if (parent != null) {
2267            FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo);
2268            shrinkAndFadeInFolderIcon(fi);
2269        }
2270        folder.animateClosed();
2271    }
2272
2273    public boolean onLongClick(View v) {
2274        if (!isDraggingEnabled()) return false;
2275        if (isWorkspaceLocked()) return false;
2276        if (mState != State.WORKSPACE) return false;
2277
2278        if (!(v instanceof CellLayout)) {
2279            v = (View) v.getParent().getParent();
2280        }
2281
2282        resetAddInfo();
2283        CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag();
2284        // This happens when long clicking an item with the dpad/trackball
2285        if (longClickCellInfo == null) {
2286            return true;
2287        }
2288
2289        // The hotseat touch handling does not go through Workspace, and we always allow long press
2290        // on hotseat items.
2291        final View itemUnderLongClick = longClickCellInfo.cell;
2292        boolean allowLongPress = isHotseatLayout(v) || mWorkspace.allowLongPress();
2293        if (allowLongPress && !mDragController.isDragging()) {
2294            if (itemUnderLongClick == null) {
2295                // User long pressed on empty space
2296                mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
2297                        HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
2298                startWallpaper();
2299            } else {
2300                if (!(itemUnderLongClick instanceof Folder)) {
2301                    // User long pressed on an item
2302                    mWorkspace.startDrag(longClickCellInfo);
2303                }
2304            }
2305        }
2306        return true;
2307    }
2308
2309    boolean isHotseatLayout(View layout) {
2310        return mHotseat != null && layout != null &&
2311                (layout instanceof CellLayout) && (layout == mHotseat.getLayout());
2312    }
2313    Hotseat getHotseat() {
2314        return mHotseat;
2315    }
2316    SearchDropTargetBar getSearchBar() {
2317        return mSearchDropTargetBar;
2318    }
2319
2320    /**
2321     * Returns the CellLayout of the specified container at the specified screen.
2322     */
2323    CellLayout getCellLayout(long container, int screen) {
2324        if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2325            if (mHotseat != null) {
2326                return mHotseat.getLayout();
2327            } else {
2328                return null;
2329            }
2330        } else {
2331            return (CellLayout) mWorkspace.getChildAt(screen);
2332        }
2333    }
2334
2335    Workspace getWorkspace() {
2336        return mWorkspace;
2337    }
2338
2339    // Now a part of LauncherModel.Callbacks. Used to reorder loading steps.
2340    public boolean isAllAppsVisible() {
2341        return (mState == State.APPS_CUSTOMIZE) || (mOnResumeState == State.APPS_CUSTOMIZE);
2342    }
2343
2344    public boolean isAllAppsButtonRank(int rank) {
2345        return mHotseat.isAllAppsButtonRank(rank);
2346    }
2347
2348    /**
2349     * Helper method for the cameraZoomIn/cameraZoomOut animations
2350     * @param view The view being animated
2351     * @param state The state that we are moving in or out of (eg. APPS_CUSTOMIZE)
2352     * @param scaleFactor The scale factor used for the zoom
2353     */
2354    private void setPivotsForZoom(View view, float scaleFactor) {
2355        view.setPivotX(view.getWidth() / 2.0f);
2356        view.setPivotY(view.getHeight() / 2.0f);
2357    }
2358
2359    void disableWallpaperIfInAllApps() {
2360        // Only disable it if we are in all apps
2361        if (isAllAppsVisible()) {
2362            if (mAppsCustomizeTabHost != null &&
2363                    !mAppsCustomizeTabHost.isTransitioning()) {
2364                updateWallpaperVisibility(false);
2365            }
2366        }
2367    }
2368
2369    void updateWallpaperVisibility(boolean visible) {
2370        int wpflags = visible ? WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER : 0;
2371        int curflags = getWindow().getAttributes().flags
2372                & WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
2373        if (wpflags != curflags) {
2374            getWindow().setFlags(wpflags, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
2375        }
2376    }
2377
2378    private void dispatchOnLauncherTransitionPrepare(View v, boolean animated, boolean toWorkspace) {
2379        if (v instanceof LauncherTransitionable) {
2380            ((LauncherTransitionable) v).onLauncherTransitionPrepare(this, animated, toWorkspace);
2381        }
2382    }
2383
2384    private void dispatchOnLauncherTransitionStart(View v, boolean animated, boolean toWorkspace) {
2385        if (v instanceof LauncherTransitionable) {
2386            ((LauncherTransitionable) v).onLauncherTransitionStart(this, animated, toWorkspace);
2387        }
2388
2389        // Update the workspace transition step as well
2390        dispatchOnLauncherTransitionStep(v, 0f);
2391    }
2392
2393    private void dispatchOnLauncherTransitionStep(View v, float t) {
2394        if (v instanceof LauncherTransitionable) {
2395            ((LauncherTransitionable) v).onLauncherTransitionStep(this, t);
2396        }
2397    }
2398
2399    private void dispatchOnLauncherTransitionEnd(View v, boolean animated, boolean toWorkspace) {
2400        if (v instanceof LauncherTransitionable) {
2401            ((LauncherTransitionable) v).onLauncherTransitionEnd(this, animated, toWorkspace);
2402        }
2403
2404        // Update the workspace transition step as well
2405        dispatchOnLauncherTransitionStep(v, 1f);
2406    }
2407
2408    /**
2409     * Things to test when changing the following seven functions.
2410     *   - Home from workspace
2411     *          - from center screen
2412     *          - from other screens
2413     *   - Home from all apps
2414     *          - from center screen
2415     *          - from other screens
2416     *   - Back from all apps
2417     *          - from center screen
2418     *          - from other screens
2419     *   - Launch app from workspace and quit
2420     *          - with back
2421     *          - with home
2422     *   - Launch app from all apps and quit
2423     *          - with back
2424     *          - with home
2425     *   - Go to a screen that's not the default, then all
2426     *     apps, and launch and app, and go back
2427     *          - with back
2428     *          -with home
2429     *   - On workspace, long press power and go back
2430     *          - with back
2431     *          - with home
2432     *   - On all apps, long press power and go back
2433     *          - with back
2434     *          - with home
2435     *   - On workspace, power off
2436     *   - On all apps, power off
2437     *   - Launch an app and turn off the screen while in that app
2438     *          - Go back with home key
2439     *          - Go back with back key  TODO: make this not go to workspace
2440     *          - From all apps
2441     *          - From workspace
2442     *   - Enter and exit car mode (becuase it causes an extra configuration changed)
2443     *          - From all apps
2444     *          - From the center workspace
2445     *          - From another workspace
2446     */
2447
2448    /**
2449     * Zoom the camera out from the workspace to reveal 'toView'.
2450     * Assumes that the view to show is anchored at either the very top or very bottom
2451     * of the screen.
2452     */
2453    private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) {
2454        if (mStateAnimation != null) {
2455            mStateAnimation.cancel();
2456            mStateAnimation = null;
2457        }
2458        final Resources res = getResources();
2459
2460        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
2461        final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
2462        final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
2463        final View fromView = mWorkspace;
2464        final AppsCustomizeTabHost toView = mAppsCustomizeTabHost;
2465        final int startDelay =
2466                res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger);
2467
2468        setPivotsForZoom(toView, scale);
2469
2470        // Shrink workspaces away if going to AppsCustomize from workspace
2471        Animator workspaceAnim =
2472                mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated);
2473
2474        if (animated) {
2475            toView.setScaleX(scale);
2476            toView.setScaleY(scale);
2477            final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView);
2478            scaleAnim.
2479                scaleX(1f).scaleY(1f).
2480                setDuration(duration).
2481                setInterpolator(new Workspace.ZoomOutInterpolator());
2482
2483            toView.setVisibility(View.VISIBLE);
2484            toView.setAlpha(0f);
2485            final ObjectAnimator alphaAnim = ObjectAnimator
2486                .ofFloat(toView, "alpha", 0f, 1f)
2487                .setDuration(fadeDuration);
2488            alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
2489            alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
2490                @Override
2491                public void onAnimationUpdate(ValueAnimator animation) {
2492                    if (animation == null) {
2493                        throw new RuntimeException("animation is null");
2494                    }
2495                    float t = (Float) animation.getAnimatedValue();
2496                    dispatchOnLauncherTransitionStep(fromView, t);
2497                    dispatchOnLauncherTransitionStep(toView, t);
2498                }
2499            });
2500
2501            // toView should appear right at the end of the workspace shrink
2502            // animation
2503            mStateAnimation = LauncherAnimUtils.createAnimatorSet();
2504            mStateAnimation.play(scaleAnim).after(startDelay);
2505            mStateAnimation.play(alphaAnim).after(startDelay);
2506
2507            mStateAnimation.addListener(new AnimatorListenerAdapter() {
2508                boolean animationCancelled = false;
2509
2510                @Override
2511                public void onAnimationStart(Animator animation) {
2512                    updateWallpaperVisibility(true);
2513                    // Prepare the position
2514                    toView.setTranslationX(0.0f);
2515                    toView.setTranslationY(0.0f);
2516                    toView.setVisibility(View.VISIBLE);
2517                    toView.bringToFront();
2518                }
2519                @Override
2520                public void onAnimationEnd(Animator animation) {
2521                    dispatchOnLauncherTransitionEnd(fromView, animated, false);
2522                    dispatchOnLauncherTransitionEnd(toView, animated, false);
2523
2524                    if (mWorkspace != null && !springLoaded && !LauncherApplication.isScreenLarge()) {
2525                        // Hide the workspace scrollbar
2526                        mWorkspace.hideScrollingIndicator(true);
2527                        hideDockDivider();
2528                    }
2529                    if (!animationCancelled) {
2530                        updateWallpaperVisibility(false);
2531                    }
2532
2533                    // Hide the search bar
2534                    if (mSearchDropTargetBar != null) {
2535                        mSearchDropTargetBar.hideSearchBar(false);
2536                    }
2537                }
2538
2539                @Override
2540                public void onAnimationCancel(Animator animation) {
2541                    animationCancelled = true;
2542                }
2543            });
2544
2545            if (workspaceAnim != null) {
2546                mStateAnimation.play(workspaceAnim);
2547            }
2548
2549            boolean delayAnim = false;
2550            final ViewTreeObserver observer;
2551
2552            dispatchOnLauncherTransitionPrepare(fromView, animated, false);
2553            dispatchOnLauncherTransitionPrepare(toView, animated, false);
2554
2555            // If any of the objects being animated haven't been measured/laid out
2556            // yet, delay the animation until we get a layout pass
2557            if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) ||
2558                    (mWorkspace.getMeasuredWidth() == 0) ||
2559                    (toView.getMeasuredWidth() == 0)) {
2560                observer = mWorkspace.getViewTreeObserver();
2561                delayAnim = true;
2562            } else {
2563                observer = null;
2564            }
2565
2566            final AnimatorSet stateAnimation = mStateAnimation;
2567            final Runnable startAnimRunnable = new Runnable() {
2568                public void run() {
2569                    // Check that mStateAnimation hasn't changed while
2570                    // we waited for a layout/draw pass
2571                    if (mStateAnimation != stateAnimation)
2572                        return;
2573                    setPivotsForZoom(toView, scale);
2574                    dispatchOnLauncherTransitionStart(fromView, animated, false);
2575                    dispatchOnLauncherTransitionStart(toView, animated, false);
2576                    toView.post(new Runnable() {
2577                        public void run() {
2578                            // Check that mStateAnimation hasn't changed while
2579                            // we waited for a layout/draw pass
2580                            if (mStateAnimation != stateAnimation)
2581                                return;
2582                            mStateAnimation.start();
2583                        }
2584                    });
2585                }
2586            };
2587            if (delayAnim) {
2588                final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() {
2589                    public void onGlobalLayout() {
2590                        toView.post(startAnimRunnable);
2591                        observer.removeOnGlobalLayoutListener(this);
2592                    }
2593                };
2594                observer.addOnGlobalLayoutListener(delayedStart);
2595            } else {
2596                startAnimRunnable.run();
2597            }
2598        } else {
2599            toView.setTranslationX(0.0f);
2600            toView.setTranslationY(0.0f);
2601            toView.setScaleX(1.0f);
2602            toView.setScaleY(1.0f);
2603            toView.setVisibility(View.VISIBLE);
2604            toView.bringToFront();
2605
2606            if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2607                // Hide the workspace scrollbar
2608                mWorkspace.hideScrollingIndicator(true);
2609                hideDockDivider();
2610
2611                // Hide the search bar
2612                if (mSearchDropTargetBar != null) {
2613                    mSearchDropTargetBar.hideSearchBar(false);
2614                }
2615            }
2616            dispatchOnLauncherTransitionPrepare(fromView, animated, false);
2617            dispatchOnLauncherTransitionStart(fromView, animated, false);
2618            dispatchOnLauncherTransitionEnd(fromView, animated, false);
2619            dispatchOnLauncherTransitionPrepare(toView, animated, false);
2620            dispatchOnLauncherTransitionStart(toView, animated, false);
2621            dispatchOnLauncherTransitionEnd(toView, animated, false);
2622            updateWallpaperVisibility(false);
2623        }
2624    }
2625
2626    /**
2627     * Zoom the camera back into the workspace, hiding 'fromView'.
2628     * This is the opposite of showAppsCustomizeHelper.
2629     * @param animated If true, the transition will be animated.
2630     */
2631    private void hideAppsCustomizeHelper(State toState, final boolean animated,
2632            final boolean springLoaded, final Runnable onCompleteRunnable) {
2633
2634        if (mStateAnimation != null) {
2635            mStateAnimation.cancel();
2636            mStateAnimation = null;
2637        }
2638        Resources res = getResources();
2639
2640        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime);
2641        final int fadeOutDuration =
2642                res.getInteger(R.integer.config_appsCustomizeFadeOutTime);
2643        final float scaleFactor = (float)
2644                res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
2645        final View fromView = mAppsCustomizeTabHost;
2646        final View toView = mWorkspace;
2647        Animator workspaceAnim = null;
2648
2649        if (toState == State.WORKSPACE) {
2650            int stagger = res.getInteger(R.integer.config_appsCustomizeWorkspaceAnimationStagger);
2651            workspaceAnim = mWorkspace.getChangeStateAnimation(
2652                    Workspace.State.NORMAL, animated, stagger);
2653        } else if (toState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
2654            workspaceAnim = mWorkspace.getChangeStateAnimation(
2655                    Workspace.State.SPRING_LOADED, animated);
2656        }
2657
2658        setPivotsForZoom(fromView, scaleFactor);
2659        updateWallpaperVisibility(true);
2660        showHotseat(animated);
2661        if (animated) {
2662            final LauncherViewPropertyAnimator scaleAnim =
2663                    new LauncherViewPropertyAnimator(fromView);
2664            scaleAnim.
2665                scaleX(scaleFactor).scaleY(scaleFactor).
2666                setDuration(duration).
2667                setInterpolator(new Workspace.ZoomInInterpolator());
2668
2669            final ObjectAnimator alphaAnim = ObjectAnimator
2670                .ofFloat(fromView, "alpha", 1f, 0f)
2671                .setDuration(fadeOutDuration);
2672            alphaAnim.setInterpolator(new AccelerateDecelerateInterpolator());
2673            alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
2674                @Override
2675                public void onAnimationUpdate(ValueAnimator animation) {
2676                    float t = 1f - (Float) animation.getAnimatedValue();
2677                    dispatchOnLauncherTransitionStep(fromView, t);
2678                    dispatchOnLauncherTransitionStep(toView, t);
2679                }
2680            });
2681
2682            mStateAnimation = LauncherAnimUtils.createAnimatorSet();
2683
2684            dispatchOnLauncherTransitionPrepare(fromView, animated, true);
2685            dispatchOnLauncherTransitionPrepare(toView, animated, true);
2686
2687            mStateAnimation.addListener(new AnimatorListenerAdapter() {
2688                @Override
2689                public void onAnimationEnd(Animator animation) {
2690                    updateWallpaperVisibility(true);
2691                    fromView.setVisibility(View.GONE);
2692                    dispatchOnLauncherTransitionEnd(fromView, animated, true);
2693                    dispatchOnLauncherTransitionEnd(toView, animated, true);
2694                    if (mWorkspace != null) {
2695                        mWorkspace.hideScrollingIndicator(false);
2696                    }
2697                    if (onCompleteRunnable != null) {
2698                        onCompleteRunnable.run();
2699                    }
2700                }
2701            });
2702
2703            mStateAnimation.playTogether(scaleAnim, alphaAnim);
2704            if (workspaceAnim != null) {
2705                mStateAnimation.play(workspaceAnim);
2706            }
2707            dispatchOnLauncherTransitionStart(fromView, animated, true);
2708            dispatchOnLauncherTransitionStart(toView, animated, true);
2709            final Animator stateAnimation = mStateAnimation;
2710            mWorkspace.post(new Runnable() {
2711                public void run() {
2712                    if (stateAnimation != mStateAnimation)
2713                        return;
2714                    mStateAnimation.start();
2715                }
2716            });
2717        } else {
2718            fromView.setVisibility(View.GONE);
2719            dispatchOnLauncherTransitionPrepare(fromView, animated, true);
2720            dispatchOnLauncherTransitionStart(fromView, animated, true);
2721            dispatchOnLauncherTransitionEnd(fromView, animated, true);
2722            dispatchOnLauncherTransitionPrepare(toView, animated, true);
2723            dispatchOnLauncherTransitionStart(toView, animated, true);
2724            dispatchOnLauncherTransitionEnd(toView, animated, true);
2725            mWorkspace.hideScrollingIndicator(false);
2726        }
2727    }
2728
2729    @Override
2730    public void onTrimMemory(int level) {
2731        super.onTrimMemory(level);
2732        if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
2733            mAppsCustomizeTabHost.onTrimMemory();
2734        }
2735    }
2736
2737    @Override
2738    public void onWindowFocusChanged(boolean hasFocus) {
2739        if (!hasFocus) {
2740            // When another window occludes launcher (like the notification shade, or recents),
2741            // ensure that we enable the wallpaper flag so that transitions are done correctly.
2742            updateWallpaperVisibility(true);
2743        } else {
2744            // When launcher has focus again, disable the wallpaper if we are in AllApps
2745            mWorkspace.postDelayed(new Runnable() {
2746                @Override
2747                public void run() {
2748                    disableWallpaperIfInAllApps();
2749                }
2750            }, 500);
2751        }
2752    }
2753
2754    void showWorkspace(boolean animated) {
2755        showWorkspace(animated, null);
2756    }
2757
2758    void showWorkspace(boolean animated, Runnable onCompleteRunnable) {
2759        if (mState != State.WORKSPACE) {
2760            boolean wasInSpringLoadedMode = (mState == State.APPS_CUSTOMIZE_SPRING_LOADED);
2761            mWorkspace.setVisibility(View.VISIBLE);
2762            hideAppsCustomizeHelper(State.WORKSPACE, animated, false, onCompleteRunnable);
2763
2764            // Show the search bar (only animate if we were showing the drop target bar in spring
2765            // loaded mode)
2766            if (mSearchDropTargetBar != null) {
2767                mSearchDropTargetBar.showSearchBar(wasInSpringLoadedMode);
2768            }
2769
2770            // We only need to animate in the dock divider if we're going from spring loaded mode
2771            showDockDivider(animated && wasInSpringLoadedMode);
2772
2773            // Set focus to the AppsCustomize button
2774            if (mAllAppsButton != null) {
2775                mAllAppsButton.requestFocus();
2776            }
2777        }
2778
2779        mWorkspace.flashScrollingIndicator(animated);
2780
2781        // Change the state *after* we've called all the transition code
2782        mState = State.WORKSPACE;
2783
2784        // Resume the auto-advance of widgets
2785        mUserPresent = true;
2786        updateRunning();
2787
2788        // send an accessibility event to announce the context change
2789        getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
2790    }
2791
2792    void showAllApps(boolean animated) {
2793        if (mState != State.WORKSPACE) return;
2794
2795        showAppsCustomizeHelper(animated, false);
2796        mAppsCustomizeTabHost.requestFocus();
2797
2798        // Change the state *after* we've called all the transition code
2799        mState = State.APPS_CUSTOMIZE;
2800
2801        // Pause the auto-advance of widgets until we are out of AllApps
2802        mUserPresent = false;
2803        updateRunning();
2804        closeFolder();
2805
2806        // Send an accessibility event to announce the context change
2807        getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
2808    }
2809
2810    void enterSpringLoadedDragMode() {
2811        if (isAllAppsVisible()) {
2812            hideAppsCustomizeHelper(State.APPS_CUSTOMIZE_SPRING_LOADED, true, true, null);
2813            hideDockDivider();
2814            mState = State.APPS_CUSTOMIZE_SPRING_LOADED;
2815        }
2816    }
2817
2818    void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, boolean extendedDelay,
2819            final Runnable onCompleteRunnable) {
2820        if (mState != State.APPS_CUSTOMIZE_SPRING_LOADED) return;
2821
2822        mHandler.postDelayed(new Runnable() {
2823            @Override
2824            public void run() {
2825                if (successfulDrop) {
2826                    // Before we show workspace, hide all apps again because
2827                    // exitSpringLoadedDragMode made it visible. This is a bit hacky; we should
2828                    // clean up our state transition functions
2829                    mAppsCustomizeTabHost.setVisibility(View.GONE);
2830                    showWorkspace(true, onCompleteRunnable);
2831                } else {
2832                    exitSpringLoadedDragMode();
2833                }
2834            }
2835        }, (extendedDelay ?
2836                EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT :
2837                EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT));
2838    }
2839
2840    void exitSpringLoadedDragMode() {
2841        if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
2842            final boolean animated = true;
2843            final boolean springLoaded = true;
2844            showAppsCustomizeHelper(animated, springLoaded);
2845            mState = State.APPS_CUSTOMIZE;
2846        }
2847        // Otherwise, we are not in spring loaded mode, so don't do anything.
2848    }
2849
2850    void hideDockDivider() {
2851        if (mQsbDivider != null && mDockDivider != null) {
2852            mQsbDivider.setVisibility(View.INVISIBLE);
2853            mDockDivider.setVisibility(View.INVISIBLE);
2854        }
2855    }
2856
2857    void showDockDivider(boolean animated) {
2858        if (mQsbDivider != null && mDockDivider != null) {
2859            mQsbDivider.setVisibility(View.VISIBLE);
2860            mDockDivider.setVisibility(View.VISIBLE);
2861            if (mDividerAnimator != null) {
2862                mDividerAnimator.cancel();
2863                mQsbDivider.setAlpha(1f);
2864                mDockDivider.setAlpha(1f);
2865                mDividerAnimator = null;
2866            }
2867            if (animated) {
2868                mDividerAnimator = LauncherAnimUtils.createAnimatorSet();
2869                mDividerAnimator.playTogether(LauncherAnimUtils.ofFloat(mQsbDivider, "alpha", 1f),
2870                        LauncherAnimUtils.ofFloat(mDockDivider, "alpha", 1f));
2871                int duration = 0;
2872                if (mSearchDropTargetBar != null) {
2873                    duration = mSearchDropTargetBar.getTransitionInDuration();
2874                }
2875                mDividerAnimator.setDuration(duration);
2876                mDividerAnimator.start();
2877            }
2878        }
2879    }
2880
2881    void lockAllApps() {
2882        // TODO
2883    }
2884
2885    void unlockAllApps() {
2886        // TODO
2887    }
2888
2889    /**
2890     * Shows the hotseat area.
2891     */
2892    void showHotseat(boolean animated) {
2893        if (!LauncherApplication.isScreenLarge()) {
2894            if (animated) {
2895                if (mHotseat.getAlpha() != 1f) {
2896                    int duration = 0;
2897                    if (mSearchDropTargetBar != null) {
2898                        duration = mSearchDropTargetBar.getTransitionInDuration();
2899                    }
2900                    mHotseat.animate().alpha(1f).setDuration(duration);
2901                }
2902            } else {
2903                mHotseat.setAlpha(1f);
2904            }
2905        }
2906    }
2907
2908    /**
2909     * Hides the hotseat area.
2910     */
2911    void hideHotseat(boolean animated) {
2912        if (!LauncherApplication.isScreenLarge()) {
2913            if (animated) {
2914                if (mHotseat.getAlpha() != 0f) {
2915                    int duration = 0;
2916                    if (mSearchDropTargetBar != null) {
2917                        duration = mSearchDropTargetBar.getTransitionOutDuration();
2918                    }
2919                    mHotseat.animate().alpha(0f).setDuration(duration);
2920                }
2921            } else {
2922                mHotseat.setAlpha(0f);
2923            }
2924        }
2925    }
2926
2927    /**
2928     * Add an item from all apps or customize onto the given workspace screen.
2929     * If layout is null, add to the current screen.
2930     */
2931    void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) {
2932        if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) {
2933            showOutOfSpaceMessage(isHotseatLayout(layout));
2934        }
2935    }
2936
2937    /** Maps the current orientation to an index for referencing orientation correct global icons */
2938    private int getCurrentOrientationIndexForGlobalIcons() {
2939        // default - 0, landscape - 1
2940        switch (getResources().getConfiguration().orientation) {
2941        case Configuration.ORIENTATION_LANDSCAPE:
2942            return 1;
2943        default:
2944            return 0;
2945        }
2946    }
2947
2948    private Drawable getExternalPackageToolbarIcon(ComponentName activityName, String resourceName) {
2949        try {
2950            PackageManager packageManager = getPackageManager();
2951            // Look for the toolbar icon specified in the activity meta-data
2952            Bundle metaData = packageManager.getActivityInfo(
2953                    activityName, PackageManager.GET_META_DATA).metaData;
2954            if (metaData != null) {
2955                int iconResId = metaData.getInt(resourceName);
2956                if (iconResId != 0) {
2957                    Resources res = packageManager.getResourcesForActivity(activityName);
2958                    return res.getDrawable(iconResId);
2959                }
2960            }
2961        } catch (NameNotFoundException e) {
2962            // This can happen if the activity defines an invalid drawable
2963            Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() +
2964                    " not found", e);
2965        } catch (Resources.NotFoundException nfe) {
2966            // This can happen if the activity defines an invalid drawable
2967            Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(),
2968                    nfe);
2969        }
2970        return null;
2971    }
2972
2973    // if successful in getting icon, return it; otherwise, set button to use default drawable
2974    private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity(
2975            int buttonId, ComponentName activityName, int fallbackDrawableId,
2976            String toolbarResourceName) {
2977        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
2978        Resources r = getResources();
2979        int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
2980        int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
2981
2982        TextView button = (TextView) findViewById(buttonId);
2983        // If we were unable to find the icon via the meta-data, use a generic one
2984        if (toolbarIcon == null) {
2985            toolbarIcon = r.getDrawable(fallbackDrawableId);
2986            toolbarIcon.setBounds(0, 0, w, h);
2987            if (button != null) {
2988                button.setCompoundDrawables(toolbarIcon, null, null, null);
2989            }
2990            return null;
2991        } else {
2992            toolbarIcon.setBounds(0, 0, w, h);
2993            if (button != null) {
2994                button.setCompoundDrawables(toolbarIcon, null, null, null);
2995            }
2996            return toolbarIcon.getConstantState();
2997        }
2998    }
2999
3000    // if successful in getting icon, return it; otherwise, set button to use default drawable
3001    private Drawable.ConstantState updateButtonWithIconFromExternalActivity(
3002            int buttonId, ComponentName activityName, int fallbackDrawableId,
3003            String toolbarResourceName) {
3004        ImageView button = (ImageView) findViewById(buttonId);
3005        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
3006
3007        if (button != null) {
3008            // If we were unable to find the icon via the meta-data, use a
3009            // generic one
3010            if (toolbarIcon == null) {
3011                button.setImageResource(fallbackDrawableId);
3012            } else {
3013                button.setImageDrawable(toolbarIcon);
3014            }
3015        }
3016
3017        return toolbarIcon != null ? toolbarIcon.getConstantState() : null;
3018
3019    }
3020
3021    private void updateTextButtonWithDrawable(int buttonId, Drawable d) {
3022        TextView button = (TextView) findViewById(buttonId);
3023        button.setCompoundDrawables(d, null, null, null);
3024    }
3025
3026    private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
3027        ImageView button = (ImageView) findViewById(buttonId);
3028        button.setImageDrawable(d.newDrawable(getResources()));
3029    }
3030
3031    private void invalidatePressedFocusedStates(View container, View button) {
3032        if (container instanceof HolographicLinearLayout) {
3033            HolographicLinearLayout layout = (HolographicLinearLayout) container;
3034            layout.invalidatePressedFocusedStates();
3035        } else if (button instanceof HolographicImageView) {
3036            HolographicImageView view = (HolographicImageView) button;
3037            view.invalidatePressedFocusedStates();
3038        }
3039    }
3040
3041    private boolean updateGlobalSearchIcon() {
3042        final View searchButtonContainer = findViewById(R.id.search_button_container);
3043        final ImageView searchButton = (ImageView) findViewById(R.id.search_button);
3044        final View voiceButtonContainer = findViewById(R.id.voice_button_container);
3045        final View voiceButton = findViewById(R.id.voice_button);
3046        final View voiceButtonProxy = findViewById(R.id.voice_button_proxy);
3047
3048        final SearchManager searchManager =
3049                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
3050        ComponentName activityName = searchManager.getGlobalSearchActivity();
3051        if (activityName != null) {
3052            int coi = getCurrentOrientationIndexForGlobalIcons();
3053            sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
3054                    R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
3055                    TOOLBAR_SEARCH_ICON_METADATA_NAME);
3056            if (sGlobalSearchIcon[coi] == null) {
3057                sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
3058                        R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
3059                        TOOLBAR_ICON_METADATA_NAME);
3060            }
3061
3062            if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.VISIBLE);
3063            searchButton.setVisibility(View.VISIBLE);
3064            invalidatePressedFocusedStates(searchButtonContainer, searchButton);
3065            return true;
3066        } else {
3067            // We disable both search and voice search when there is no global search provider
3068            if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.GONE);
3069            if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
3070            searchButton.setVisibility(View.GONE);
3071            voiceButton.setVisibility(View.GONE);
3072            if (voiceButtonProxy != null) {
3073                voiceButtonProxy.setVisibility(View.GONE);
3074            }
3075            return false;
3076        }
3077    }
3078
3079    private void updateGlobalSearchIcon(Drawable.ConstantState d) {
3080        final View searchButtonContainer = findViewById(R.id.search_button_container);
3081        final View searchButton = (ImageView) findViewById(R.id.search_button);
3082        updateButtonWithDrawable(R.id.search_button, d);
3083        invalidatePressedFocusedStates(searchButtonContainer, searchButton);
3084    }
3085
3086    private boolean updateVoiceSearchIcon(boolean searchVisible) {
3087        final View voiceButtonContainer = findViewById(R.id.voice_button_container);
3088        final View voiceButton = findViewById(R.id.voice_button);
3089        final View voiceButtonProxy = findViewById(R.id.voice_button_proxy);
3090
3091        // We only show/update the voice search icon if the search icon is enabled as well
3092        final SearchManager searchManager =
3093                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
3094        ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
3095
3096        ComponentName activityName = null;
3097        if (globalSearchActivity != null) {
3098            // Check if the global search activity handles voice search
3099            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
3100            intent.setPackage(globalSearchActivity.getPackageName());
3101            activityName = intent.resolveActivity(getPackageManager());
3102        }
3103
3104        if (activityName == null) {
3105            // Fallback: check if an activity other than the global search activity
3106            // resolves this
3107            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
3108            activityName = intent.resolveActivity(getPackageManager());
3109        }
3110        if (searchVisible && activityName != null) {
3111            int coi = getCurrentOrientationIndexForGlobalIcons();
3112            sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
3113                    R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
3114                    TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME);
3115            if (sVoiceSearchIcon[coi] == null) {
3116                sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
3117                        R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
3118                        TOOLBAR_ICON_METADATA_NAME);
3119            }
3120            if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.VISIBLE);
3121            voiceButton.setVisibility(View.VISIBLE);
3122            if (voiceButtonProxy != null) {
3123                voiceButtonProxy.setVisibility(View.VISIBLE);
3124            }
3125            invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
3126            return true;
3127        } else {
3128            if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
3129            voiceButton.setVisibility(View.GONE);
3130            if (voiceButtonProxy != null) {
3131                voiceButtonProxy.setVisibility(View.GONE);
3132            }
3133            return false;
3134        }
3135    }
3136
3137    private void updateVoiceSearchIcon(Drawable.ConstantState d) {
3138        final View voiceButtonContainer = findViewById(R.id.voice_button_container);
3139        final View voiceButton = findViewById(R.id.voice_button);
3140        updateButtonWithDrawable(R.id.voice_button, d);
3141        invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
3142    }
3143
3144    /**
3145     * Sets the app market icon
3146     */
3147    private void updateAppMarketIcon() {
3148        final View marketButton = findViewById(R.id.market_button);
3149        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
3150        // Find the app market activity by resolving an intent.
3151        // (If multiple app markets are installed, it will return the ResolverActivity.)
3152        ComponentName activityName = intent.resolveActivity(getPackageManager());
3153        if (activityName != null) {
3154            int coi = getCurrentOrientationIndexForGlobalIcons();
3155            mAppMarketIntent = intent;
3156            sAppMarketIcon[coi] = updateTextButtonWithIconFromExternalActivity(
3157                    R.id.market_button, activityName, R.drawable.ic_launcher_market_holo,
3158                    TOOLBAR_ICON_METADATA_NAME);
3159            marketButton.setVisibility(View.VISIBLE);
3160        } else {
3161            // We should hide and disable the view so that we don't try and restore the visibility
3162            // of it when we swap between drag & normal states from IconDropTarget subclasses.
3163            marketButton.setVisibility(View.GONE);
3164            marketButton.setEnabled(false);
3165        }
3166    }
3167
3168    private void updateAppMarketIcon(Drawable.ConstantState d) {
3169        // Ensure that the new drawable we are creating has the approprate toolbar icon bounds
3170        Resources r = getResources();
3171        Drawable marketIconDrawable = d.newDrawable(r);
3172        int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
3173        int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
3174        marketIconDrawable.setBounds(0, 0, w, h);
3175
3176        updateTextButtonWithDrawable(R.id.market_button, marketIconDrawable);
3177    }
3178
3179    @Override
3180    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3181        boolean result = super.dispatchPopulateAccessibilityEvent(event);
3182        final List<CharSequence> text = event.getText();
3183        text.clear();
3184        text.add(getString(R.string.home));
3185        return result;
3186    }
3187
3188    /**
3189     * Receives notifications when system dialogs are to be closed.
3190     */
3191    private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
3192        @Override
3193        public void onReceive(Context context, Intent intent) {
3194            closeSystemDialogs();
3195        }
3196    }
3197
3198    /**
3199     * Receives notifications whenever the appwidgets are reset.
3200     */
3201    private class AppWidgetResetObserver extends ContentObserver {
3202        public AppWidgetResetObserver() {
3203            super(new Handler());
3204        }
3205
3206        @Override
3207        public void onChange(boolean selfChange) {
3208            onAppWidgetReset();
3209        }
3210    }
3211
3212    /**
3213     * If the activity is currently paused, signal that we need to re-run the loader
3214     * in onResume.
3215     *
3216     * This needs to be called from incoming places where resources might have been loaded
3217     * while we are paused.  That is becaues the Configuration might be wrong
3218     * when we're not running, and if it comes back to what it was when we
3219     * were paused, we are not restarted.
3220     *
3221     * Implementation of the method from LauncherModel.Callbacks.
3222     *
3223     * @return true if we are currently paused.  The caller might be able to
3224     * skip some work in that case since we will come back again.
3225     */
3226    public boolean setLoadOnResume() {
3227        if (mPaused) {
3228            Log.i(TAG, "setLoadOnResume");
3229            mOnResumeNeedsLoad = true;
3230            return true;
3231        } else {
3232            return false;
3233        }
3234    }
3235
3236    /**
3237     * Implementation of the method from LauncherModel.Callbacks.
3238     */
3239    public int getCurrentWorkspaceScreen() {
3240        if (mWorkspace != null) {
3241            return mWorkspace.getCurrentPage();
3242        } else {
3243            return SCREEN_COUNT / 2;
3244        }
3245    }
3246
3247    /**
3248     * Refreshes the shortcuts shown on the workspace.
3249     *
3250     * Implementation of the method from LauncherModel.Callbacks.
3251     */
3252    public void startBinding() {
3253        final Workspace workspace = mWorkspace;
3254
3255        mNewShortcutAnimatePage = -1;
3256        mNewShortcutAnimateViews.clear();
3257        mWorkspace.clearDropTargets();
3258        int count = workspace.getChildCount();
3259        for (int i = 0; i < count; i++) {
3260            // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
3261            final CellLayout layoutParent = (CellLayout) workspace.getChildAt(i);
3262            layoutParent.removeAllViewsInLayout();
3263        }
3264        mWidgetsToAdvance.clear();
3265        if (mHotseat != null) {
3266            mHotseat.resetLayout();
3267        }
3268    }
3269
3270    /**
3271     * Bind the items start-end from the list.
3272     *
3273     * Implementation of the method from LauncherModel.Callbacks.
3274     */
3275    public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
3276        setLoadOnResume();
3277
3278        // Get the list of added shortcuts and intersect them with the set of shortcuts here
3279        Set<String> newApps = new HashSet<String>();
3280        newApps = mSharedPrefs.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, newApps);
3281
3282        Workspace workspace = mWorkspace;
3283        for (int i = start; i < end; i++) {
3284            final ItemInfo item = shortcuts.get(i);
3285
3286            // Short circuit if we are loading dock items for a configuration which has no dock
3287            if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
3288                    mHotseat == null) {
3289                continue;
3290            }
3291
3292            switch (item.itemType) {
3293                case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3294                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3295                    ShortcutInfo info = (ShortcutInfo) item;
3296                    String uri = info.intent.toUri(0).toString();
3297                    View shortcut = createShortcut(info);
3298                    workspace.addInScreen(shortcut, item.container, item.screen, item.cellX,
3299                            item.cellY, 1, 1, false);
3300                    boolean animateIconUp = false;
3301                    synchronized (newApps) {
3302                        if (newApps.contains(uri)) {
3303                            animateIconUp = newApps.remove(uri);
3304                        }
3305                    }
3306                    if (animateIconUp) {
3307                        // Prepare the view to be animated up
3308                        shortcut.setAlpha(0f);
3309                        shortcut.setScaleX(0f);
3310                        shortcut.setScaleY(0f);
3311                        mNewShortcutAnimatePage = item.screen;
3312                        if (!mNewShortcutAnimateViews.contains(shortcut)) {
3313                            mNewShortcutAnimateViews.add(shortcut);
3314                        }
3315                    }
3316                    break;
3317                case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3318                    FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
3319                            (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
3320                            (FolderInfo) item, mIconCache);
3321                    workspace.addInScreen(newFolder, item.container, item.screen, item.cellX,
3322                            item.cellY, 1, 1, false);
3323                    break;
3324            }
3325        }
3326
3327        workspace.requestLayout();
3328    }
3329
3330    /**
3331     * Implementation of the method from LauncherModel.Callbacks.
3332     */
3333    public void bindFolders(HashMap<Long, FolderInfo> folders) {
3334        setLoadOnResume();
3335        sFolders.clear();
3336        sFolders.putAll(folders);
3337    }
3338
3339    /**
3340     * Add the views for a widget to the workspace.
3341     *
3342     * Implementation of the method from LauncherModel.Callbacks.
3343     */
3344    public void bindAppWidget(LauncherAppWidgetInfo item) {
3345        setLoadOnResume();
3346
3347        final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
3348        if (DEBUG_WIDGETS) {
3349            Log.d(TAG, "bindAppWidget: " + item);
3350        }
3351        final Workspace workspace = mWorkspace;
3352
3353        final int appWidgetId = item.appWidgetId;
3354        final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
3355        if (DEBUG_WIDGETS) {
3356            Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
3357        }
3358
3359        item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
3360
3361        item.hostView.setTag(item);
3362        item.onBindAppWidget(this);
3363
3364        workspace.addInScreen(item.hostView, item.container, item.screen, item.cellX,
3365                item.cellY, item.spanX, item.spanY, false);
3366        addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
3367
3368        workspace.requestLayout();
3369
3370        if (DEBUG_WIDGETS) {
3371            Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
3372                    + (SystemClock.uptimeMillis()-start) + "ms");
3373        }
3374    }
3375
3376    public void onPageBoundSynchronously(int page) {
3377        mSynchronouslyBoundPages.add(page);
3378    }
3379
3380    /**
3381     * Callback saying that there aren't any more items to bind.
3382     *
3383     * Implementation of the method from LauncherModel.Callbacks.
3384     */
3385    public void finishBindingItems() {
3386        setLoadOnResume();
3387
3388        if (mSavedState != null) {
3389            if (!mWorkspace.hasFocus()) {
3390                mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
3391            }
3392            mSavedState = null;
3393        }
3394
3395        mWorkspace.restoreInstanceStateForRemainingPages();
3396
3397        // If we received the result of any pending adds while the loader was running (e.g. the
3398        // widget configuration forced an orientation change), process them now.
3399        for (int i = 0; i < sPendingAddList.size(); i++) {
3400            completeAdd(sPendingAddList.get(i));
3401        }
3402        sPendingAddList.clear();
3403
3404        // Update the market app icon as necessary (the other icons will be managed in response to
3405        // package changes in bindSearchablesChanged()
3406        updateAppMarketIcon();
3407
3408        // Animate up any icons as necessary
3409        if (mVisible || mWorkspaceLoading) {
3410            Runnable newAppsRunnable = new Runnable() {
3411                @Override
3412                public void run() {
3413                    runNewAppsAnimation(false);
3414                }
3415            };
3416
3417            boolean willSnapPage = mNewShortcutAnimatePage > -1 &&
3418                    mNewShortcutAnimatePage != mWorkspace.getCurrentPage();
3419            if (canRunNewAppsAnimation()) {
3420                // If the user has not interacted recently, then either snap to the new page to show
3421                // the new-apps animation or just run them if they are to appear on the current page
3422                if (willSnapPage) {
3423                    mWorkspace.snapToPage(mNewShortcutAnimatePage, newAppsRunnable);
3424                } else {
3425                    runNewAppsAnimation(false);
3426                }
3427            } else {
3428                // If the user has interacted recently, then just add the items in place if they
3429                // are on another page (or just normally if they are added to the current page)
3430                runNewAppsAnimation(willSnapPage);
3431            }
3432        }
3433
3434        mWorkspaceLoading = false;
3435    }
3436
3437    private boolean canRunNewAppsAnimation() {
3438        long diff = System.currentTimeMillis() - mDragController.getLastGestureUpTime();
3439        return diff > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000);
3440    }
3441
3442    /**
3443     * Runs a new animation that scales up icons that were added while Launcher was in the
3444     * background.
3445     *
3446     * @param immediate whether to run the animation or show the results immediately
3447     */
3448    private void runNewAppsAnimation(boolean immediate) {
3449        AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
3450        Collection<Animator> bounceAnims = new ArrayList<Animator>();
3451
3452        // Order these new views spatially so that they animate in order
3453        Collections.sort(mNewShortcutAnimateViews, new Comparator<View>() {
3454            @Override
3455            public int compare(View a, View b) {
3456                CellLayout.LayoutParams alp = (CellLayout.LayoutParams) a.getLayoutParams();
3457                CellLayout.LayoutParams blp = (CellLayout.LayoutParams) b.getLayoutParams();
3458                int cellCountX = LauncherModel.getCellCountX();
3459                return (alp.cellY * cellCountX + alp.cellX) - (blp.cellY * cellCountX + blp.cellX);
3460            }
3461        });
3462
3463        // Animate each of the views in place (or show them immediately if requested)
3464        if (immediate) {
3465            for (View v : mNewShortcutAnimateViews) {
3466                v.setAlpha(1f);
3467                v.setScaleX(1f);
3468                v.setScaleY(1f);
3469            }
3470        } else {
3471            for (int i = 0; i < mNewShortcutAnimateViews.size(); ++i) {
3472                View v = mNewShortcutAnimateViews.get(i);
3473                ValueAnimator bounceAnim = LauncherAnimUtils.ofPropertyValuesHolder(v,
3474                        PropertyValuesHolder.ofFloat("alpha", 1f),
3475                        PropertyValuesHolder.ofFloat("scaleX", 1f),
3476                        PropertyValuesHolder.ofFloat("scaleY", 1f));
3477                bounceAnim.setDuration(InstallShortcutReceiver.NEW_SHORTCUT_BOUNCE_DURATION);
3478                bounceAnim.setStartDelay(i * InstallShortcutReceiver.NEW_SHORTCUT_STAGGER_DELAY);
3479                bounceAnim.setInterpolator(new SmoothPagedView.OvershootInterpolator());
3480                bounceAnims.add(bounceAnim);
3481            }
3482            anim.playTogether(bounceAnims);
3483            anim.addListener(new AnimatorListenerAdapter() {
3484                @Override
3485                public void onAnimationEnd(Animator animation) {
3486                    mWorkspace.postDelayed(mBuildLayersRunnable, 500);
3487                }
3488            });
3489            anim.start();
3490        }
3491
3492        // Clean up
3493        mNewShortcutAnimatePage = -1;
3494        mNewShortcutAnimateViews.clear();
3495        new Thread("clearNewAppsThread") {
3496            public void run() {
3497                mSharedPrefs.edit()
3498                            .putInt(InstallShortcutReceiver.NEW_APPS_PAGE_KEY, -1)
3499                            .putStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, null)
3500                            .commit();
3501            }
3502        }.start();
3503    }
3504
3505    @Override
3506    public void bindSearchablesChanged() {
3507        boolean searchVisible = updateGlobalSearchIcon();
3508        boolean voiceVisible = updateVoiceSearchIcon(searchVisible);
3509        if (mSearchDropTargetBar != null) {
3510            mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
3511        }
3512    }
3513
3514    /**
3515     * Add the icons for all apps.
3516     *
3517     * Implementation of the method from LauncherModel.Callbacks.
3518     */
3519    public void bindAllApplications(final ArrayList<ApplicationInfo> apps) {
3520        Runnable setAllAppsRunnable = new Runnable() {
3521            public void run() {
3522                if (mAppsCustomizeContent != null) {
3523                    mAppsCustomizeContent.setApps(apps);
3524                }
3525            }
3526        };
3527
3528        // Remove the progress bar entirely; we could also make it GONE
3529        // but better to remove it since we know it's not going to be used
3530        View progressBar = mAppsCustomizeTabHost.
3531            findViewById(R.id.apps_customize_progress_bar);
3532        if (progressBar != null) {
3533            ((ViewGroup)progressBar.getParent()).removeView(progressBar);
3534
3535            // We just post the call to setApps so the user sees the progress bar
3536            // disappear-- otherwise, it just looks like the progress bar froze
3537            // which doesn't look great
3538            mAppsCustomizeTabHost.post(setAllAppsRunnable);
3539        } else {
3540            // If we did not initialize the spinner in onCreate, then we can directly set the
3541            // list of applications without waiting for any progress bars views to be hidden.
3542            setAllAppsRunnable.run();
3543        }
3544    }
3545
3546    /**
3547     * A package was installed.
3548     *
3549     * Implementation of the method from LauncherModel.Callbacks.
3550     */
3551    public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {
3552        setLoadOnResume();
3553
3554        if (mAppsCustomizeContent != null) {
3555            mAppsCustomizeContent.addApps(apps);
3556        }
3557    }
3558
3559    /**
3560     * A package was updated.
3561     *
3562     * Implementation of the method from LauncherModel.Callbacks.
3563     */
3564    public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) {
3565        setLoadOnResume();
3566        if (mWorkspace != null) {
3567            mWorkspace.updateShortcuts(apps);
3568        }
3569
3570        if (mAppsCustomizeContent != null) {
3571            mAppsCustomizeContent.updateApps(apps);
3572        }
3573    }
3574
3575    /**
3576     * A package was uninstalled.
3577     *
3578     * Implementation of the method from LauncherModel.Callbacks.
3579     */
3580    public void bindAppsRemoved(ArrayList<String> packageNames, boolean permanent) {
3581        if (permanent) {
3582            mWorkspace.removeItems(packageNames);
3583        }
3584
3585        if (mAppsCustomizeContent != null) {
3586            mAppsCustomizeContent.removeApps(packageNames);
3587        }
3588
3589        // Notify the drag controller
3590        mDragController.onAppsRemoved(packageNames, this);
3591    }
3592
3593    /**
3594     * A number of packages were updated.
3595     */
3596    public void bindPackagesUpdated() {
3597        if (mAppsCustomizeContent != null) {
3598            mAppsCustomizeContent.onPackagesUpdated();
3599        }
3600    }
3601
3602    private int mapConfigurationOriActivityInfoOri(int configOri) {
3603        final Display d = getWindowManager().getDefaultDisplay();
3604        int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
3605        switch (d.getRotation()) {
3606        case Surface.ROTATION_0:
3607        case Surface.ROTATION_180:
3608            // We are currently in the same basic orientation as the natural orientation
3609            naturalOri = configOri;
3610            break;
3611        case Surface.ROTATION_90:
3612        case Surface.ROTATION_270:
3613            // We are currently in the other basic orientation to the natural orientation
3614            naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
3615                    Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
3616            break;
3617        }
3618
3619        int[] oriMap = {
3620                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
3621                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
3622                ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
3623                ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
3624        };
3625        // Since the map starts at portrait, we need to offset if this device's natural orientation
3626        // is landscape.
3627        int indexOffset = 0;
3628        if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
3629            indexOffset = 1;
3630        }
3631        return oriMap[(d.getRotation() + indexOffset) % 4];
3632    }
3633
3634    public boolean isRotationEnabled() {
3635        boolean forceEnableRotation = doesFileExist(FORCE_ENABLE_ROTATION_PROPERTY);
3636        boolean enableRotation = forceEnableRotation ||
3637                getResources().getBoolean(R.bool.allow_rotation);
3638        return enableRotation;
3639    }
3640    public void lockScreenOrientation() {
3641        if (isRotationEnabled()) {
3642            setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
3643                    .getConfiguration().orientation));
3644        }
3645    }
3646    public void unlockScreenOrientation(boolean immediate) {
3647        if (isRotationEnabled()) {
3648            if (immediate) {
3649                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
3650            } else {
3651                mHandler.postDelayed(new Runnable() {
3652                    public void run() {
3653                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
3654                    }
3655                }, mRestoreScreenOrientationDelay);
3656            }
3657        }
3658    }
3659
3660    /* Cling related */
3661    private boolean isClingsEnabled() {
3662        // disable clings when running in a test harness
3663        if(ActivityManager.isRunningInTestHarness()) return false;
3664
3665        return true;
3666    }
3667
3668    private Cling initCling(int clingId, int[] positionData, boolean animate, int delay) {
3669        final Cling cling = (Cling) findViewById(clingId);
3670        if (cling != null) {
3671            cling.init(this, positionData);
3672            cling.setVisibility(View.VISIBLE);
3673            cling.setLayerType(View.LAYER_TYPE_HARDWARE, null);
3674            if (animate) {
3675                cling.buildLayer();
3676                cling.setAlpha(0f);
3677                cling.animate()
3678                    .alpha(1f)
3679                    .setInterpolator(new AccelerateInterpolator())
3680                    .setDuration(SHOW_CLING_DURATION)
3681                    .setStartDelay(delay)
3682                    .start();
3683            } else {
3684                cling.setAlpha(1f);
3685            }
3686            cling.setFocusableInTouchMode(true);
3687            cling.post(new Runnable() {
3688                public void run() {
3689                    cling.setFocusable(true);
3690                    cling.requestFocus();
3691                }
3692            });
3693            mHideFromAccessibilityHelper.setImportantForAccessibilityToNo(
3694                    mDragLayer, clingId == R.id.all_apps_cling);
3695        }
3696        return cling;
3697    }
3698
3699    private void dismissCling(final Cling cling, final String flag, int duration) {
3700        if (cling != null && cling.getVisibility() == View.VISIBLE) {
3701            ObjectAnimator anim = LauncherAnimUtils.ofFloat(cling, "alpha", 0f);
3702            anim.setDuration(duration);
3703            anim.addListener(new AnimatorListenerAdapter() {
3704                public void onAnimationEnd(Animator animation) {
3705                    cling.setVisibility(View.GONE);
3706                    cling.cleanup();
3707                    // We should update the shared preferences on a background thread
3708                    new Thread("dismissClingThread") {
3709                        public void run() {
3710                            SharedPreferences.Editor editor = mSharedPrefs.edit();
3711                            editor.putBoolean(flag, true);
3712                            editor.commit();
3713                        }
3714                    }.start();
3715                };
3716            });
3717            anim.start();
3718            mHideFromAccessibilityHelper.restoreImportantForAccessibility(mDragLayer);
3719        }
3720    }
3721
3722    private void removeCling(int id) {
3723        final View cling = findViewById(id);
3724        if (cling != null) {
3725            final ViewGroup parent = (ViewGroup) cling.getParent();
3726            parent.post(new Runnable() {
3727                @Override
3728                public void run() {
3729                    parent.removeView(cling);
3730                }
3731            });
3732            mHideFromAccessibilityHelper.restoreImportantForAccessibility(mDragLayer);
3733        }
3734    }
3735
3736    private boolean skipCustomClingIfNoAccounts() {
3737        Cling cling = (Cling) findViewById(R.id.workspace_cling);
3738        boolean customCling = cling.getDrawIdentifier().equals("workspace_custom");
3739        if (customCling) {
3740            AccountManager am = AccountManager.get(this);
3741            Account[] accounts = am.getAccountsByType("com.google");
3742            return accounts.length == 0;
3743        }
3744        return false;
3745    }
3746
3747    public void showFirstRunWorkspaceCling() {
3748        // Enable the clings only if they have not been dismissed before
3749        if (isClingsEnabled() &&
3750                !mSharedPrefs.getBoolean(Cling.WORKSPACE_CLING_DISMISSED_KEY, false) &&
3751                !skipCustomClingIfNoAccounts() ) {
3752            // If we're not using the default workspace layout, replace workspace cling
3753            // with a custom workspace cling (usually specified in an overlay)
3754            // For now, only do this on tablets
3755            if (mSharedPrefs.getInt(LauncherProvider.DEFAULT_WORKSPACE_RESOURCE_ID, 0) != 0 &&
3756                    getResources().getBoolean(R.bool.config_useCustomClings)) {
3757                // Use a custom cling
3758                View cling = findViewById(R.id.workspace_cling);
3759                ViewGroup clingParent = (ViewGroup) cling.getParent();
3760                int clingIndex = clingParent.indexOfChild(cling);
3761                clingParent.removeViewAt(clingIndex);
3762                View customCling = mInflater.inflate(R.layout.custom_workspace_cling, clingParent, false);
3763                clingParent.addView(customCling, clingIndex);
3764                customCling.setId(R.id.workspace_cling);
3765            }
3766            initCling(R.id.workspace_cling, null, false, 0);
3767        } else {
3768            removeCling(R.id.workspace_cling);
3769        }
3770    }
3771    public void showFirstRunAllAppsCling(int[] position) {
3772        // Enable the clings only if they have not been dismissed before
3773        if (isClingsEnabled() &&
3774                !mSharedPrefs.getBoolean(Cling.ALLAPPS_CLING_DISMISSED_KEY, false)) {
3775            initCling(R.id.all_apps_cling, position, true, 0);
3776        } else {
3777            removeCling(R.id.all_apps_cling);
3778        }
3779    }
3780    public Cling showFirstRunFoldersCling() {
3781        // Enable the clings only if they have not been dismissed before
3782        if (isClingsEnabled() &&
3783                !mSharedPrefs.getBoolean(Cling.FOLDER_CLING_DISMISSED_KEY, false)) {
3784            return initCling(R.id.folder_cling, null, true, 0);
3785        } else {
3786            removeCling(R.id.folder_cling);
3787            return null;
3788        }
3789    }
3790    public boolean isFolderClingVisible() {
3791        Cling cling = (Cling) findViewById(R.id.folder_cling);
3792        if (cling != null) {
3793            return cling.getVisibility() == View.VISIBLE;
3794        }
3795        return false;
3796    }
3797    public void dismissWorkspaceCling(View v) {
3798        Cling cling = (Cling) findViewById(R.id.workspace_cling);
3799        dismissCling(cling, Cling.WORKSPACE_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
3800    }
3801    public void dismissAllAppsCling(View v) {
3802        Cling cling = (Cling) findViewById(R.id.all_apps_cling);
3803        dismissCling(cling, Cling.ALLAPPS_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
3804    }
3805    public void dismissFolderCling(View v) {
3806        Cling cling = (Cling) findViewById(R.id.folder_cling);
3807        dismissCling(cling, Cling.FOLDER_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
3808    }
3809
3810    /**
3811     * Prints out out state for debugging.
3812     */
3813    public void dumpState() {
3814        Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this);
3815        Log.d(TAG, "mSavedState=" + mSavedState);
3816        Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
3817        Log.d(TAG, "mRestoring=" + mRestoring);
3818        Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
3819        Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
3820        Log.d(TAG, "sFolders.size=" + sFolders.size());
3821        mModel.dumpState();
3822
3823        if (mAppsCustomizeContent != null) {
3824            mAppsCustomizeContent.dumpState();
3825        }
3826        Log.d(TAG, "END launcher2 dump state");
3827    }
3828
3829    @Override
3830    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
3831        super.dump(prefix, fd, writer, args);
3832        writer.println(" ");
3833        writer.println("Debug logs: ");
3834        for (int i = 0; i < sDumpLogs.size(); i++) {
3835            writer.println("  " + sDumpLogs.get(i));
3836        }
3837    }
3838
3839    public static void dumpDebugLogsToConsole() {
3840        Log.d(TAG, "");
3841        Log.d(TAG, "*********************");
3842        Log.d(TAG, "Launcher debug logs: ");
3843        for (int i = 0; i < sDumpLogs.size(); i++) {
3844            Log.d(TAG, "  " + sDumpLogs.get(i));
3845        }
3846        Log.d(TAG, "*********************");
3847        Log.d(TAG, "");
3848    }
3849}
3850
3851interface LauncherTransitionable {
3852    View getContent();
3853    void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace);
3854    void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace);
3855    void onLauncherTransitionStep(Launcher l, float t);
3856    void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace);
3857}
3858