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