Launcher.java revision 7ad0141905fffe5bc359581fd3001abb10d3b730
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.launcher2;
18
19import com.android.common.Search;
20
21import android.app.Activity;
22import android.app.AlertDialog;
23import android.app.Dialog;
24import android.app.SearchManager;
25import android.app.StatusBarManager;
26import android.app.WallpaperManager;
27import android.content.ActivityNotFoundException;
28import android.content.BroadcastReceiver;
29import android.content.ComponentName;
30import android.content.ContentResolver;
31import android.content.Context;
32import android.content.DialogInterface;
33import android.content.Intent;
34import android.content.Intent.ShortcutIconResource;
35import android.content.IntentFilter;
36import android.content.pm.ActivityInfo;
37import android.content.pm.PackageManager;
38import android.content.pm.ResolveInfo;
39import android.content.res.Configuration;
40import android.content.res.Resources;
41import android.content.res.TypedArray;
42import android.database.ContentObserver;
43import android.graphics.Bitmap;
44import android.graphics.Rect;
45import android.graphics.Canvas;
46import android.graphics.drawable.Drawable;
47import android.graphics.drawable.ColorDrawable;
48import android.net.Uri;
49import android.os.AsyncTask;
50import android.os.Bundle;
51import android.os.Handler;
52import android.os.Parcelable;
53import android.os.SystemClock;
54import android.os.SystemProperties;
55import android.provider.LiveFolders;
56import android.text.Selection;
57import android.text.SpannableStringBuilder;
58import android.text.TextUtils;
59import android.text.method.TextKeyListener;
60import android.util.Log;
61import android.view.Display;
62import android.view.HapticFeedbackConstants;
63import android.view.KeyEvent;
64import android.view.LayoutInflater;
65import android.view.Menu;
66import android.view.MenuItem;
67import android.view.View;
68import android.view.ViewGroup;
69import android.view.View.OnLongClickListener;
70import android.view.inputmethod.InputMethodManager;
71import android.widget.EditText;
72import android.widget.TextView;
73import android.widget.Toast;
74import android.widget.ImageView;
75import android.widget.PopupWindow;
76import android.widget.LinearLayout;
77import android.appwidget.AppWidgetManager;
78import android.appwidget.AppWidgetProviderInfo;
79
80import java.util.ArrayList;
81import java.util.List;
82import java.util.HashMap;
83import java.io.DataOutputStream;
84import java.io.FileNotFoundException;
85import java.io.IOException;
86import java.io.DataInputStream;
87
88import com.android.launcher.R;
89
90/**
91 * Default launcher application.
92 */
93public final class Launcher extends Activity
94        implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks, AllAppsView.Watcher {
95    static final String TAG = "Launcher";
96    static final boolean LOGD = false;
97
98    static final boolean PROFILE_STARTUP = false;
99    static final boolean DEBUG_WIDGETS = false;
100    static final boolean DEBUG_USER_INTERFACE = false;
101
102    private static final int WALLPAPER_SCREENS_SPAN = 2;
103
104    private static final int MENU_GROUP_ADD = 1;
105    private static final int MENU_GROUP_WALLPAPER = MENU_GROUP_ADD + 1;
106
107    private static final int MENU_ADD = Menu.FIRST + 1;
108    private static final int MENU_MANAGE_APPS = MENU_ADD + 1;
109    private static final int MENU_WALLPAPER_SETTINGS = MENU_MANAGE_APPS + 1;
110    private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1;
111    private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1;
112    private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1;
113
114    private static final int REQUEST_CREATE_SHORTCUT = 1;
115    private static final int REQUEST_CREATE_LIVE_FOLDER = 4;
116    private static final int REQUEST_CREATE_APPWIDGET = 5;
117    private static final int REQUEST_PICK_APPLICATION = 6;
118    private static final int REQUEST_PICK_SHORTCUT = 7;
119    private static final int REQUEST_PICK_LIVE_FOLDER = 8;
120    private static final int REQUEST_PICK_APPWIDGET = 9;
121    private static final int REQUEST_PICK_WALLPAPER = 10;
122
123    static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
124
125    static final int SCREEN_COUNT = 5;
126    static final int DEFAULT_SCREEN = 2;
127    static final int NUMBER_CELLS_X = 4;
128    static final int NUMBER_CELLS_Y = 4;
129
130    static final int DIALOG_CREATE_SHORTCUT = 1;
131    static final int DIALOG_RENAME_FOLDER = 2;
132
133    private static final String PREFERENCES = "launcher.preferences";
134
135    // Type: int
136    private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
137    // Type: boolean
138    private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder";
139    // Type: long
140    private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder";
141    // Type: int
142    private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
143    // Type: int
144    private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX";
145    // Type: int
146    private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY";
147    // Type: int
148    private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX";
149    // Type: int
150    private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY";
151    // Type: int
152    private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX";
153    // Type: int
154    private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY";
155    // Type: int[]
156    private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells";
157    // Type: boolean
158    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
159    // Type: long
160    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
161
162    static final int APPWIDGET_HOST_ID = 1024;
163
164    private static final Object sLock = new Object();
165    private static int sScreen = DEFAULT_SCREEN;
166
167    private final BroadcastReceiver mCloseSystemDialogsReceiver
168            = new CloseSystemDialogsIntentReceiver();
169    private final ContentObserver mWidgetObserver = new AppWidgetResetObserver();
170
171    private LayoutInflater mInflater;
172
173    private DragController mDragController;
174    private Workspace mWorkspace;
175
176    private AppWidgetManager mAppWidgetManager;
177    private LauncherAppWidgetHost mAppWidgetHost;
178
179    private CellLayout.CellInfo mAddItemCellInfo;
180    private CellLayout.CellInfo mMenuAddInfo;
181    private final int[] mCellCoordinates = new int[2];
182    private FolderInfo mFolderInfo;
183
184    private DeleteZone mDeleteZone;
185    private HandleView mHandleView;
186    private AllAppsView mAllAppsGrid;
187
188    private Bundle mSavedState;
189
190    private SpannableStringBuilder mDefaultKeySsb = null;
191
192    private boolean mWorkspaceLoading = true;
193
194    private boolean mPaused = true;
195    private boolean mRestoring;
196    private boolean mWaitingForResult;
197
198    private Bundle mSavedInstanceState;
199
200    private LauncherModel mModel;
201    private IconCache mIconCache;
202
203    private static LocaleConfiguration sLocaleConfiguration = null;
204
205    private ArrayList<ItemInfo> mDesktopItems = new ArrayList<ItemInfo>();
206    private static HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
207
208    private ImageView mPreviousView;
209    private ImageView mNextView;
210
211    // Hotseats (quick-launch icons next to AllApps)
212    private static final int NUM_HOTSEATS = 2;
213    private String[] mHotseatConfig = null;
214    private Intent[] mHotseats = null;
215    private Drawable[] mHotseatIcons = null;
216    private CharSequence[] mHotseatLabels = null;
217
218    @Override
219    protected void onCreate(Bundle savedInstanceState) {
220        super.onCreate(savedInstanceState);
221
222        LauncherApplication app = ((LauncherApplication)getApplication());
223        mModel = app.setLauncher(this);
224        mIconCache = app.getIconCache();
225        mDragController = new DragController(this);
226        mInflater = getLayoutInflater();
227
228        mAppWidgetManager = AppWidgetManager.getInstance(this);
229        mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
230        mAppWidgetHost.startListening();
231
232        if (PROFILE_STARTUP) {
233            android.os.Debug.startMethodTracing("/sdcard/launcher");
234        }
235
236        loadHotseats();
237        checkForLocaleChange();
238        setWallpaperDimension();
239
240        setContentView(R.layout.launcher);
241        setupViews();
242
243        registerContentObservers();
244
245        lockAllApps();
246
247        mSavedState = savedInstanceState;
248        restoreState(mSavedState);
249
250        if (PROFILE_STARTUP) {
251            android.os.Debug.stopMethodTracing();
252        }
253
254        if (!mRestoring) {
255            mModel.startLoader(this, true);
256        }
257
258        // For handling default keys
259        mDefaultKeySsb = new SpannableStringBuilder();
260        Selection.setSelection(mDefaultKeySsb, 0);
261
262        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
263        registerReceiver(mCloseSystemDialogsReceiver, filter);
264    }
265
266    private void checkForLocaleChange() {
267        if (sLocaleConfiguration == null) {
268            new AsyncTask<Void, Void, LocaleConfiguration>() {
269                @Override
270                protected LocaleConfiguration doInBackground(Void... unused) {
271                    LocaleConfiguration localeConfiguration = new LocaleConfiguration();
272                    readConfiguration(Launcher.this, localeConfiguration);
273                    return localeConfiguration;
274                }
275
276                @Override
277                protected void onPostExecute(LocaleConfiguration result) {
278                    sLocaleConfiguration = result;
279                    checkForLocaleChange();  // recursive, but now with a locale configuration
280                }
281            }.execute();
282            return;
283        }
284
285        final Configuration configuration = getResources().getConfiguration();
286
287        final String previousLocale = sLocaleConfiguration.locale;
288        final String locale = configuration.locale.toString();
289
290        final int previousMcc = sLocaleConfiguration.mcc;
291        final int mcc = configuration.mcc;
292
293        final int previousMnc = sLocaleConfiguration.mnc;
294        final int mnc = configuration.mnc;
295
296        boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
297
298        if (localeChanged) {
299            sLocaleConfiguration.locale = locale;
300            sLocaleConfiguration.mcc = mcc;
301            sLocaleConfiguration.mnc = mnc;
302
303            mIconCache.flush();
304            loadHotseats();
305
306            final LocaleConfiguration localeConfiguration = sLocaleConfiguration;
307            new Thread("WriteLocaleConfiguration") {
308                public void run() {
309                    writeConfiguration(Launcher.this, localeConfiguration);
310                }
311            }.start();
312        }
313    }
314
315    private static class LocaleConfiguration {
316        public String locale;
317        public int mcc = -1;
318        public int mnc = -1;
319    }
320
321    private static void readConfiguration(Context context, LocaleConfiguration configuration) {
322        DataInputStream in = null;
323        try {
324            in = new DataInputStream(context.openFileInput(PREFERENCES));
325            configuration.locale = in.readUTF();
326            configuration.mcc = in.readInt();
327            configuration.mnc = in.readInt();
328        } catch (FileNotFoundException e) {
329            // Ignore
330        } catch (IOException e) {
331            // Ignore
332        } finally {
333            if (in != null) {
334                try {
335                    in.close();
336                } catch (IOException e) {
337                    // Ignore
338                }
339            }
340        }
341    }
342
343    private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
344        DataOutputStream out = null;
345        try {
346            out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
347            out.writeUTF(configuration.locale);
348            out.writeInt(configuration.mcc);
349            out.writeInt(configuration.mnc);
350            out.flush();
351        } catch (FileNotFoundException e) {
352            // Ignore
353        } catch (IOException e) {
354            //noinspection ResultOfMethodCallIgnored
355            context.getFileStreamPath(PREFERENCES).delete();
356        } finally {
357            if (out != null) {
358                try {
359                    out.close();
360                } catch (IOException e) {
361                    // Ignore
362                }
363            }
364        }
365    }
366
367    static int getScreen() {
368        synchronized (sLock) {
369            return sScreen;
370        }
371    }
372
373    static void setScreen(int screen) {
374        synchronized (sLock) {
375            sScreen = screen;
376        }
377    }
378
379    private void setWallpaperDimension() {
380        WallpaperManager wpm = (WallpaperManager)getSystemService(WALLPAPER_SERVICE);
381
382        Display display = getWindowManager().getDefaultDisplay();
383        boolean isPortrait = display.getWidth() < display.getHeight();
384
385        final int width = isPortrait ? display.getWidth() : display.getHeight();
386        final int height = isPortrait ? display.getHeight() : display.getWidth();
387        wpm.suggestDesiredDimensions(width * WALLPAPER_SCREENS_SPAN, height);
388    }
389
390    // Note: This doesn't do all the client-id magic that BrowserProvider does
391    // in Browser. (http://b/2425179)
392    private Uri getDefaultBrowserUri() {
393        String url = getString(R.string.default_browser_url);
394        if (url.indexOf("{CID}") != -1) {
395            url = url.replace("{CID}", "android-google");
396        }
397        return Uri.parse(url);
398    }
399
400    // Load the Intent templates from arrays.xml to populate the hotseats. For
401    // each Intent, if it resolves to a single app, use that as the launch
402    // intent & use that app's label as the contentDescription. Otherwise,
403    // retain the ResolveActivity so the user can pick an app.
404    private void loadHotseats() {
405        if (mHotseatConfig == null) {
406            mHotseatConfig = getResources().getStringArray(R.array.hotseats);
407            if (mHotseatConfig.length > 0) {
408                mHotseats = new Intent[mHotseatConfig.length];
409                mHotseatLabels = new CharSequence[mHotseatConfig.length];
410                mHotseatIcons = new Drawable[mHotseatConfig.length];
411            } else {
412                mHotseats = null;
413                mHotseatIcons = null;
414                mHotseatLabels = null;
415            }
416
417            TypedArray hotseatIconDrawables = getResources().obtainTypedArray(R.array.hotseat_icons);
418            for (int i=0; i<mHotseatConfig.length; i++) {
419                // load icon for this slot; currently unrelated to the actual activity
420                try {
421                    mHotseatIcons[i] = hotseatIconDrawables.getDrawable(i);
422                } catch (ArrayIndexOutOfBoundsException ex) {
423                    Log.w(TAG, "Missing hotseat_icons array item #" + i);
424                    mHotseatIcons[i] = null;
425                }
426            }
427            hotseatIconDrawables.recycle();
428        }
429
430        PackageManager pm = getPackageManager();
431        for (int i=0; i<mHotseatConfig.length; i++) {
432            Intent intent = null;
433            if (mHotseatConfig[i].equals("*BROWSER*")) {
434                // magic value meaning "launch user's default web browser"
435                // replace it with a generic web request so we can see if there is indeed a default
436                String defaultUri = getString(R.string.default_browser_url);
437                intent = new Intent(
438                        Intent.ACTION_VIEW,
439                        ((defaultUri != null)
440                            ? Uri.parse(defaultUri)
441                            : getDefaultBrowserUri())
442                    ).addCategory(Intent.CATEGORY_BROWSABLE);
443                // note: if the user launches this without a default set, she
444                // will always be taken to the default URL above; this is
445                // unavoidable as we must specify a valid URL in order for the
446                // chooser to appear, and once the user selects something, that
447                // URL is unavoidably sent to the chosen app.
448            } else {
449                try {
450                    intent = Intent.parseUri(mHotseatConfig[i], 0);
451                } catch (java.net.URISyntaxException ex) {
452                    Log.w(TAG, "Invalid hotseat intent: " + mHotseatConfig[i]);
453                    // bogus; leave intent=null
454                }
455            }
456
457            if (intent == null) {
458                mHotseats[i] = null;
459                mHotseatLabels[i] = getText(R.string.activity_not_found);
460                continue;
461            }
462
463            if (LOGD) {
464                Log.d(TAG, "loadHotseats: hotseat " + i
465                    + " initial intent=["
466                    + intent.toUri(Intent.URI_INTENT_SCHEME)
467                    + "]");
468            }
469
470            ResolveInfo bestMatch = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
471            List<ResolveInfo> allMatches = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
472            if (LOGD) {
473                Log.d(TAG, "Best match for intent: " + bestMatch);
474                Log.d(TAG, "All matches: ");
475                for (ResolveInfo ri : allMatches) {
476                    Log.d(TAG, "  --> " + ri);
477                }
478            }
479            // did this resolve to a single app, or the resolver?
480            if (allMatches.size() == 0 || bestMatch == null) {
481                // can't find any activity to handle this. let's leave the
482                // intent as-is and let Launcher show a toast when it fails
483                // to launch.
484                mHotseats[i] = intent;
485
486                // set accessibility text to "Not installed"
487                mHotseatLabels[i] = getText(R.string.activity_not_found);
488            } else {
489                boolean found = false;
490                for (ResolveInfo ri : allMatches) {
491                    if (bestMatch.activityInfo.name.equals(ri.activityInfo.name)
492                        && bestMatch.activityInfo.applicationInfo.packageName
493                            .equals(ri.activityInfo.applicationInfo.packageName)) {
494                        found = true;
495                        break;
496                    }
497                }
498
499                if (!found) {
500                    if (LOGD) Log.d(TAG, "Multiple options, no default yet");
501                    // the bestMatch is probably the ResolveActivity, meaning the
502                    // user has not yet selected a default
503                    // so: we'll keep the original intent for now
504                    mHotseats[i] = intent;
505
506                    // set the accessibility text to "Select shortcut"
507                    mHotseatLabels[i] = getText(R.string.title_select_shortcut);
508                } else {
509                    // we have an app!
510                    // now reconstruct the intent to launch it through the front
511                    // door
512                    ComponentName com = new ComponentName(
513                        bestMatch.activityInfo.applicationInfo.packageName,
514                        bestMatch.activityInfo.name);
515                    mHotseats[i] = new Intent(Intent.ACTION_MAIN).setComponent(com);
516
517                    // load the app label for accessibility
518                    mHotseatLabels[i] = bestMatch.activityInfo.loadLabel(pm);
519                }
520            }
521
522            if (LOGD) {
523                Log.d(TAG, "loadHotseats: hotseat " + i
524                    + " final intent=["
525                    + ((mHotseats[i] == null)
526                        ? "null"
527                        : mHotseats[i].toUri(Intent.URI_INTENT_SCHEME))
528                    + "] label=[" + mHotseatLabels[i]
529                    + "]"
530                    );
531            }
532        }
533    }
534
535    @Override
536    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
537        mWaitingForResult = false;
538
539        // The pattern used here is that a user PICKs a specific application,
540        // which, depending on the target, might need to CREATE the actual target.
541
542        // For example, the user would PICK_SHORTCUT for "Music playlist", and we
543        // launch over to the Music app to actually CREATE_SHORTCUT.
544
545        if (resultCode == RESULT_OK && mAddItemCellInfo != null) {
546            switch (requestCode) {
547                case REQUEST_PICK_APPLICATION:
548                    completeAddApplication(this, data, mAddItemCellInfo);
549                    break;
550                case REQUEST_PICK_SHORTCUT:
551                    processShortcut(data);
552                    break;
553                case REQUEST_CREATE_SHORTCUT:
554                    completeAddShortcut(data, mAddItemCellInfo);
555                    break;
556                case REQUEST_PICK_LIVE_FOLDER:
557                    addLiveFolder(data);
558                    break;
559                case REQUEST_CREATE_LIVE_FOLDER:
560                    completeAddLiveFolder(data, mAddItemCellInfo);
561                    break;
562                case REQUEST_PICK_APPWIDGET:
563                    addAppWidget(data);
564                    break;
565                case REQUEST_CREATE_APPWIDGET:
566                    completeAddAppWidget(data, mAddItemCellInfo);
567                    break;
568                case REQUEST_PICK_WALLPAPER:
569                    // We just wanted the activity result here so we can clear mWaitingForResult
570                    break;
571            }
572        } else if ((requestCode == REQUEST_PICK_APPWIDGET ||
573                requestCode == REQUEST_CREATE_APPWIDGET) && resultCode == RESULT_CANCELED &&
574                data != null) {
575            // Clean up the appWidgetId if we canceled
576            int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
577            if (appWidgetId != -1) {
578                mAppWidgetHost.deleteAppWidgetId(appWidgetId);
579            }
580        }
581    }
582
583    @Override
584    protected void onResume() {
585        super.onResume();
586
587        mPaused = false;
588
589        if (mRestoring) {
590            mWorkspaceLoading = true;
591            mModel.startLoader(this, true);
592            mRestoring = false;
593        }
594    }
595
596    @Override
597    protected void onPause() {
598        super.onPause();
599        dismissPreview(mPreviousView);
600        dismissPreview(mNextView);
601        mDragController.cancelDrag();
602    }
603
604    @Override
605    public Object onRetainNonConfigurationInstance() {
606        // Flag the loader to stop early before switching
607        mModel.stopLoader();
608        mAllAppsGrid.surrender();
609        return Boolean.TRUE;
610    }
611
612    // We can't hide the IME if it was forced open.  So don't bother
613    /*
614    @Override
615    public void onWindowFocusChanged(boolean hasFocus) {
616        super.onWindowFocusChanged(hasFocus);
617
618        if (hasFocus) {
619            final InputMethodManager inputManager = (InputMethodManager)
620                    getSystemService(Context.INPUT_METHOD_SERVICE);
621            WindowManager.LayoutParams lp = getWindow().getAttributes();
622            inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new
623                        android.os.Handler()) {
624                        protected void onReceiveResult(int resultCode, Bundle resultData) {
625                            Log.d(TAG, "ResultReceiver got resultCode=" + resultCode);
626                        }
627                    });
628            Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged");
629        }
630    }
631    */
632
633    private boolean acceptFilter() {
634        final InputMethodManager inputManager = (InputMethodManager)
635                getSystemService(Context.INPUT_METHOD_SERVICE);
636        return !inputManager.isFullscreenMode();
637    }
638
639    @Override
640    public boolean onKeyDown(int keyCode, KeyEvent event) {
641        boolean handled = super.onKeyDown(keyCode, event);
642        if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) {
643            boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
644                    keyCode, event);
645            if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
646                // something usable has been typed - start a search
647                // the typed text will be retrieved and cleared by
648                // showSearchDialog()
649                // If there are multiple keystrokes before the search dialog takes focus,
650                // onSearchRequested() will be called for every keystroke,
651                // but it is idempotent, so it's fine.
652                return onSearchRequested();
653            }
654        }
655
656        // Eat the long press event so the keyboard doesn't come up.
657        if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
658            return true;
659        }
660
661        return handled;
662    }
663
664    private String getTypedText() {
665        return mDefaultKeySsb.toString();
666    }
667
668    private void clearTypedText() {
669        mDefaultKeySsb.clear();
670        mDefaultKeySsb.clearSpans();
671        Selection.setSelection(mDefaultKeySsb, 0);
672    }
673
674    /**
675     * Restores the previous state, if it exists.
676     *
677     * @param savedState The previous state.
678     */
679    private void restoreState(Bundle savedState) {
680        if (savedState == null) {
681            return;
682        }
683
684        final boolean allApps = savedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false);
685        if (allApps) {
686            showAllApps(false);
687        }
688
689        final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
690        if (currentScreen > -1) {
691            mWorkspace.setCurrentScreen(currentScreen);
692        }
693
694        final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
695        if (addScreen > -1) {
696            mAddItemCellInfo = new CellLayout.CellInfo();
697            final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
698            addItemCellInfo.valid = true;
699            addItemCellInfo.screen = addScreen;
700            addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
701            addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
702            addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
703            addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
704            addItemCellInfo.findVacantCellsFromOccupied(
705                    savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
706                    savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
707                    savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
708            mRestoring = true;
709        }
710
711        boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
712        if (renameFolder) {
713            long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
714            mFolderInfo = mModel.getFolderById(this, sFolders, id);
715            mRestoring = true;
716        }
717    }
718
719    /**
720     * Finds all the views we need and configure them properly.
721     */
722    private void setupViews() {
723        DragController dragController = mDragController;
724
725        DragLayer dragLayer = (DragLayer) findViewById(R.id.drag_layer);
726        dragLayer.setDragController(dragController);
727
728        mAllAppsGrid = (AllAppsView)dragLayer.findViewById(R.id.all_apps_view);
729        mAllAppsGrid.setLauncher(this);
730        mAllAppsGrid.setDragController(dragController);
731        ((View) mAllAppsGrid).setWillNotDraw(false); // We don't want a hole punched in our window.
732        // Manage focusability manually since this thing is always visible
733        ((View) mAllAppsGrid).setFocusable(false);
734
735        mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
736        final Workspace workspace = mWorkspace;
737        workspace.setHapticFeedbackEnabled(false);
738
739        DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone);
740        mDeleteZone = deleteZone;
741
742        mHandleView = (HandleView) findViewById(R.id.all_apps_button);
743        mHandleView.setLauncher(this);
744        mHandleView.setOnClickListener(this);
745        mHandleView.setOnLongClickListener(this);
746
747        ImageView hotseatLeft = (ImageView) findViewById(R.id.hotseat_left);
748        hotseatLeft.setContentDescription(mHotseatLabels[0]);
749        hotseatLeft.setImageDrawable(mHotseatIcons[0]);
750        ImageView hotseatRight = (ImageView) findViewById(R.id.hotseat_right);
751        hotseatRight.setContentDescription(mHotseatLabels[1]);
752        hotseatRight.setImageDrawable(mHotseatIcons[1]);
753
754        mPreviousView = (ImageView) dragLayer.findViewById(R.id.previous_screen);
755        mNextView = (ImageView) dragLayer.findViewById(R.id.next_screen);
756
757        Drawable previous = mPreviousView.getDrawable();
758        Drawable next = mNextView.getDrawable();
759        mWorkspace.setIndicators(previous, next);
760
761        mPreviousView.setHapticFeedbackEnabled(false);
762        mPreviousView.setOnLongClickListener(this);
763        mNextView.setHapticFeedbackEnabled(false);
764        mNextView.setOnLongClickListener(this);
765
766        workspace.setOnLongClickListener(this);
767        workspace.setDragController(dragController);
768        workspace.setLauncher(this);
769
770        deleteZone.setLauncher(this);
771        deleteZone.setDragController(dragController);
772        deleteZone.setHandle(findViewById(R.id.all_apps_button_cluster));
773
774        dragController.setDragScoller(workspace);
775        dragController.setDragListener(deleteZone);
776        dragController.setScrollView(dragLayer);
777        dragController.setMoveTarget(workspace);
778
779        // The order here is bottom to top.
780        dragController.addDropTarget(workspace);
781        dragController.addDropTarget(deleteZone);
782    }
783
784    @SuppressWarnings({"UnusedDeclaration"})
785    public void previousScreen(View v) {
786        if (!isAllAppsVisible()) {
787            mWorkspace.scrollLeft();
788        }
789    }
790
791    @SuppressWarnings({"UnusedDeclaration"})
792    public void nextScreen(View v) {
793        if (!isAllAppsVisible()) {
794            mWorkspace.scrollRight();
795        }
796    }
797
798    @SuppressWarnings({"UnusedDeclaration"})
799    public void launchHotSeat(View v) {
800        if (isAllAppsVisible()) return;
801
802        int index = -1;
803        if (v.getId() == R.id.hotseat_left) {
804            index = 0;
805        } else if (v.getId() == R.id.hotseat_right) {
806            index = 1;
807        }
808
809        // reload these every tap; you never know when they might change
810        loadHotseats();
811        if (index >= 0 && index < mHotseats.length && mHotseats[index] != null) {
812            Intent intent = mHotseats[index];
813            startActivitySafely(
814                mHotseats[index],
815                "hotseat"
816            );
817        }
818    }
819
820    /**
821     * Creates a view representing a shortcut.
822     *
823     * @param info The data structure describing the shortcut.
824     *
825     * @return A View inflated from R.layout.application.
826     */
827    View createShortcut(ShortcutInfo info) {
828        return createShortcut(R.layout.application,
829                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
830    }
831
832    /**
833     * Creates a view representing a shortcut inflated from the specified resource.
834     *
835     * @param layoutResId The id of the XML layout used to create the shortcut.
836     * @param parent The group the shortcut belongs to.
837     * @param info The data structure describing the shortcut.
838     *
839     * @return A View inflated from layoutResId.
840     */
841    View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) {
842        TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false);
843
844        favorite.setCompoundDrawablesWithIntrinsicBounds(null,
845                new FastBitmapDrawable(info.getIcon(mIconCache)),
846                null, null);
847        favorite.setText(info.title);
848        favorite.setTag(info);
849        favorite.setOnClickListener(this);
850
851        return favorite;
852    }
853
854    /**
855     * Add an application shortcut to the workspace.
856     *
857     * @param data The intent describing the application.
858     * @param cellInfo The position on screen where to create the shortcut.
859     */
860    void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo) {
861        cellInfo.screen = mWorkspace.getCurrentScreen();
862        if (!findSingleSlot(cellInfo)) return;
863
864        final ShortcutInfo info = mModel.getShortcutInfo(context.getPackageManager(),
865                data, context);
866
867        if (info != null) {
868            info.setActivity(data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK |
869                    Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
870            info.container = ItemInfo.NO_ID;
871            mWorkspace.addApplicationShortcut(info, cellInfo, isWorkspaceLocked());
872        } else {
873            Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data);
874        }
875    }
876
877    /**
878     * Add a shortcut to the workspace.
879     *
880     * @param data The intent describing the shortcut.
881     * @param cellInfo The position on screen where to create the shortcut.
882     */
883    private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo) {
884        cellInfo.screen = mWorkspace.getCurrentScreen();
885        if (!findSingleSlot(cellInfo)) return;
886
887        final ShortcutInfo info = mModel.addShortcut(this, data, cellInfo, false);
888
889        if (!mRestoring) {
890            final View view = createShortcut(info);
891            mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1,
892                    isWorkspaceLocked());
893        }
894    }
895
896
897    /**
898     * Add a widget to the workspace.
899     *
900     * @param data The intent describing the appWidgetId.
901     * @param cellInfo The position on screen where to create the widget.
902     */
903    private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo) {
904        Bundle extras = data.getExtras();
905        int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
906
907        if (LOGD) Log.d(TAG, "dumping extras content=" + extras.toString());
908
909        AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
910
911        // Calculate the grid spans needed to fit this widget
912        CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen);
913        int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight);
914
915        // Try finding open space on Launcher screen
916        final int[] xy = mCellCoordinates;
917        if (!findSlot(cellInfo, xy, spans[0], spans[1])) {
918            if (appWidgetId != -1) mAppWidgetHost.deleteAppWidgetId(appWidgetId);
919            return;
920        }
921
922        // Build Launcher-specific widget info and save to database
923        LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
924        launcherInfo.spanX = spans[0];
925        launcherInfo.spanY = spans[1];
926
927        LauncherModel.addItemToDatabase(this, launcherInfo,
928                LauncherSettings.Favorites.CONTAINER_DESKTOP,
929                mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
930
931        if (!mRestoring) {
932            mDesktopItems.add(launcherInfo);
933
934            // Perform actual inflation because we're live
935            launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
936
937            launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
938            launcherInfo.hostView.setTag(launcherInfo);
939
940            mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1],
941                    launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
942        }
943    }
944
945    public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
946        mDesktopItems.remove(launcherInfo);
947        launcherInfo.hostView = null;
948    }
949
950    public LauncherAppWidgetHost getAppWidgetHost() {
951        return mAppWidgetHost;
952    }
953
954    void closeSystemDialogs() {
955        getWindow().closeAllPanels();
956
957        try {
958            dismissDialog(DIALOG_CREATE_SHORTCUT);
959            // Unlock the workspace if the dialog was showing
960        } catch (Exception e) {
961            // An exception is thrown if the dialog is not visible, which is fine
962        }
963
964        try {
965            dismissDialog(DIALOG_RENAME_FOLDER);
966            // Unlock the workspace if the dialog was showing
967        } catch (Exception e) {
968            // An exception is thrown if the dialog is not visible, which is fine
969        }
970
971        // Whatever we were doing is hereby canceled.
972        mWaitingForResult = false;
973    }
974
975    @Override
976    protected void onNewIntent(Intent intent) {
977        super.onNewIntent(intent);
978
979        // Close the menu
980        if (Intent.ACTION_MAIN.equals(intent.getAction())) {
981            // also will cancel mWaitingForResult.
982            closeSystemDialogs();
983
984            boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
985                        != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
986            boolean allAppsVisible = isAllAppsVisible();
987            if (!mWorkspace.isDefaultScreenShowing()) {
988                mWorkspace.moveToDefaultScreen(alreadyOnHome && !allAppsVisible);
989            }
990            closeAllApps(alreadyOnHome && allAppsVisible);
991
992            final View v = getWindow().peekDecorView();
993            if (v != null && v.getWindowToken() != null) {
994                InputMethodManager imm = (InputMethodManager)getSystemService(
995                        INPUT_METHOD_SERVICE);
996                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
997            }
998        }
999    }
1000
1001    @Override
1002    protected void onRestoreInstanceState(Bundle savedInstanceState) {
1003        // Do not call super here
1004        mSavedInstanceState = savedInstanceState;
1005    }
1006
1007    @Override
1008    protected void onSaveInstanceState(Bundle outState) {
1009        outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen());
1010
1011        final ArrayList<Folder> folders = mWorkspace.getOpenFolders();
1012        if (folders.size() > 0) {
1013            final int count = folders.size();
1014            long[] ids = new long[count];
1015            for (int i = 0; i < count; i++) {
1016                final FolderInfo info = folders.get(i).getInfo();
1017                ids[i] = info.id;
1018            }
1019            outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
1020        } else {
1021            super.onSaveInstanceState(outState);
1022        }
1023
1024        // TODO should not do this if the drawer is currently closing.
1025        if (isAllAppsVisible()) {
1026            outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true);
1027        }
1028
1029        if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) {
1030            final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
1031            final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen);
1032
1033            outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen);
1034            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX);
1035            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY);
1036            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX);
1037            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY);
1038            outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX());
1039            outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY());
1040            outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS,
1041                   layout.getOccupiedCells());
1042        }
1043
1044        if (mFolderInfo != null && mWaitingForResult) {
1045            outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
1046            outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
1047        }
1048    }
1049
1050    @Override
1051    public void onDestroy() {
1052        super.onDestroy();
1053
1054        try {
1055            mAppWidgetHost.stopListening();
1056        } catch (NullPointerException ex) {
1057            Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
1058        }
1059
1060        TextKeyListener.getInstance().release();
1061
1062        mModel.stopLoader();
1063
1064        unbindDesktopItems();
1065
1066        getContentResolver().unregisterContentObserver(mWidgetObserver);
1067
1068        dismissPreview(mPreviousView);
1069        dismissPreview(mNextView);
1070
1071        unregisterReceiver(mCloseSystemDialogsReceiver);
1072    }
1073
1074    @Override
1075    public void startActivityForResult(Intent intent, int requestCode) {
1076        if (requestCode >= 0) mWaitingForResult = true;
1077        super.startActivityForResult(intent, requestCode);
1078    }
1079
1080    @Override
1081    public void startSearch(String initialQuery, boolean selectInitialQuery,
1082            Bundle appSearchData, boolean globalSearch) {
1083
1084        closeAllApps(true);
1085
1086        if (initialQuery == null) {
1087            // Use any text typed in the launcher as the initial query
1088            initialQuery = getTypedText();
1089            clearTypedText();
1090        }
1091        if (appSearchData == null) {
1092            appSearchData = new Bundle();
1093            appSearchData.putString(Search.SOURCE, "launcher-search");
1094        }
1095
1096        final SearchManager searchManager =
1097                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
1098        searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
1099            appSearchData, globalSearch);
1100    }
1101
1102    @Override
1103    public boolean onCreateOptionsMenu(Menu menu) {
1104        if (isWorkspaceLocked()) {
1105            return false;
1106        }
1107
1108        super.onCreateOptionsMenu(menu);
1109
1110        menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
1111                .setIcon(android.R.drawable.ic_menu_add)
1112                .setAlphabeticShortcut('A');
1113        menu.add(0, MENU_MANAGE_APPS, 0, R.string.menu_manage_apps)
1114                .setIcon(android.R.drawable.ic_menu_manage)
1115                .setAlphabeticShortcut('M');
1116        menu.add(MENU_GROUP_WALLPAPER, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
1117                 .setIcon(android.R.drawable.ic_menu_gallery)
1118                 .setAlphabeticShortcut('W');
1119        menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
1120                .setIcon(android.R.drawable.ic_search_category_default)
1121                .setAlphabeticShortcut(SearchManager.MENU_KEY);
1122        menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
1123                .setIcon(com.android.internal.R.drawable.ic_menu_notifications)
1124                .setAlphabeticShortcut('N');
1125
1126        final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
1127        settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1128                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1129
1130        menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
1131                .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
1132                .setIntent(settings);
1133
1134        return true;
1135    }
1136
1137    @Override
1138    public boolean onPrepareOptionsMenu(Menu menu) {
1139        super.onPrepareOptionsMenu(menu);
1140
1141        // If all apps is animating, don't show the menu, because we don't know
1142        // which one to show.
1143        if (mAllAppsGrid.isVisible() && !mAllAppsGrid.isOpaque()) {
1144            return false;
1145        }
1146
1147        // Only show the add and wallpaper options when we're not in all apps.
1148        boolean visible = !mAllAppsGrid.isOpaque();
1149        menu.setGroupVisible(MENU_GROUP_ADD, visible);
1150        menu.setGroupVisible(MENU_GROUP_WALLPAPER, visible);
1151
1152        // Disable add if the workspace is full.
1153        if (visible) {
1154            mMenuAddInfo = mWorkspace.findAllVacantCells(null);
1155            menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid);
1156        }
1157
1158        return true;
1159    }
1160
1161    @Override
1162    public boolean onOptionsItemSelected(MenuItem item) {
1163        switch (item.getItemId()) {
1164            case MENU_ADD:
1165                addItems();
1166                return true;
1167            case MENU_MANAGE_APPS:
1168                manageApps();
1169                return true;
1170            case MENU_WALLPAPER_SETTINGS:
1171                startWallpaper();
1172                return true;
1173            case MENU_SEARCH:
1174                onSearchRequested();
1175                return true;
1176            case MENU_NOTIFICATIONS:
1177                showNotifications();
1178                return true;
1179        }
1180
1181        return super.onOptionsItemSelected(item);
1182    }
1183
1184    /**
1185     * Indicates that we want global search for this activity by setting the globalSearch
1186     * argument for {@link #startSearch} to true.
1187     */
1188
1189    @Override
1190    public boolean onSearchRequested() {
1191        startSearch(null, false, null, true);
1192        return true;
1193    }
1194
1195    public boolean isWorkspaceLocked() {
1196        return mWorkspaceLoading || mWaitingForResult;
1197    }
1198
1199    private void addItems() {
1200        closeAllApps(true);
1201        showAddDialog(mMenuAddInfo);
1202    }
1203
1204    private void manageApps() {
1205        startActivity(new Intent(android.provider.Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS));
1206    }
1207
1208    void addAppWidget(Intent data) {
1209        // TODO: catch bad widget exception when sent
1210        int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
1211        AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1212
1213        if (appWidget.configure != null) {
1214            // Launch over to configure widget, if needed
1215            Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
1216            intent.setComponent(appWidget.configure);
1217            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1218
1219            startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET);
1220        } else {
1221            // Otherwise just add it
1222            onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
1223        }
1224    }
1225
1226    void processShortcut(Intent intent) {
1227        // Handle case where user selected "Applications"
1228        String applicationName = getResources().getString(R.string.group_applications);
1229        String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1230
1231        if (applicationName != null && applicationName.equals(shortcutName)) {
1232            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1233            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1234
1235            Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1236            pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1237            startActivityForResultSafely(pickIntent, REQUEST_PICK_APPLICATION);
1238        } else {
1239            startActivityForResultSafely(intent, REQUEST_CREATE_SHORTCUT);
1240        }
1241    }
1242
1243    void addLiveFolder(Intent intent) {
1244        // Handle case where user selected "Folder"
1245        String folderName = getResources().getString(R.string.group_folder);
1246        String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1247
1248        if (folderName != null && folderName.equals(shortcutName)) {
1249            addFolder();
1250        } else {
1251            startActivityForResultSafely(intent, REQUEST_CREATE_LIVE_FOLDER);
1252        }
1253    }
1254
1255    void addFolder() {
1256        UserFolderInfo folderInfo = new UserFolderInfo();
1257        folderInfo.title = getText(R.string.folder_name);
1258
1259        CellLayout.CellInfo cellInfo = mAddItemCellInfo;
1260        cellInfo.screen = mWorkspace.getCurrentScreen();
1261        if (!findSingleSlot(cellInfo)) return;
1262
1263        // Update the model
1264        LauncherModel.addItemToDatabase(this, folderInfo,
1265                LauncherSettings.Favorites.CONTAINER_DESKTOP,
1266                mWorkspace.getCurrentScreen(), cellInfo.cellX, cellInfo.cellY, false);
1267        sFolders.put(folderInfo.id, folderInfo);
1268
1269        // Create the view
1270        FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1271                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo);
1272        mWorkspace.addInCurrentScreen(newFolder,
1273                cellInfo.cellX, cellInfo.cellY, 1, 1, isWorkspaceLocked());
1274    }
1275
1276    void removeFolder(FolderInfo folder) {
1277        sFolders.remove(folder.id);
1278    }
1279
1280    private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo) {
1281        cellInfo.screen = mWorkspace.getCurrentScreen();
1282        if (!findSingleSlot(cellInfo)) return;
1283
1284        final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);
1285
1286        if (!mRestoring) {
1287            final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this,
1288                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
1289            mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1,
1290                    isWorkspaceLocked());
1291        }
1292    }
1293
1294    static LiveFolderInfo addLiveFolder(Context context, Intent data,
1295            CellLayout.CellInfo cellInfo, boolean notify) {
1296
1297        Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
1298        String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);
1299
1300        Drawable icon = null;
1301        Intent.ShortcutIconResource iconResource = null;
1302
1303        Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);
1304        if (extra != null && extra instanceof Intent.ShortcutIconResource) {
1305            try {
1306                iconResource = (Intent.ShortcutIconResource) extra;
1307                final PackageManager packageManager = context.getPackageManager();
1308                Resources resources = packageManager.getResourcesForApplication(
1309                        iconResource.packageName);
1310                final int id = resources.getIdentifier(iconResource.resourceName, null, null);
1311                icon = resources.getDrawable(id);
1312            } catch (Exception e) {
1313                Log.w(TAG, "Could not load live folder icon: " + extra);
1314            }
1315        }
1316
1317        if (icon == null) {
1318            icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder);
1319        }
1320
1321        final LiveFolderInfo info = new LiveFolderInfo();
1322        info.icon = Utilities.createIconBitmap(icon, context);
1323        info.title = name;
1324        info.iconResource = iconResource;
1325        info.uri = data.getData();
1326        info.baseIntent = baseIntent;
1327        info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
1328                LiveFolders.DISPLAY_MODE_GRID);
1329
1330        LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1331                cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
1332        sFolders.put(info.id, info);
1333
1334        return info;
1335    }
1336
1337    private boolean findSingleSlot(CellLayout.CellInfo cellInfo) {
1338        final int[] xy = new int[2];
1339        if (findSlot(cellInfo, xy, 1, 1)) {
1340            cellInfo.cellX = xy[0];
1341            cellInfo.cellY = xy[1];
1342            return true;
1343        }
1344        return false;
1345    }
1346
1347    private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) {
1348        if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1349            boolean[] occupied = mSavedState != null ?
1350                    mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null;
1351            cellInfo = mWorkspace.findAllVacantCells(occupied);
1352            if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1353                Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1354                return false;
1355            }
1356        }
1357        return true;
1358    }
1359
1360    private void showNotifications() {
1361        final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1362        if (statusBar != null) {
1363            statusBar.expand();
1364        }
1365    }
1366
1367    private void startWallpaper() {
1368        closeAllApps(true);
1369        final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1370        Intent chooser = Intent.createChooser(pickWallpaper,
1371                getText(R.string.chooser_wallpaper));
1372        // NOTE: Adds a configure option to the chooser if the wallpaper supports it
1373        //       Removed in Eclair MR1
1374//        WallpaperManager wm = (WallpaperManager)
1375//                getSystemService(Context.WALLPAPER_SERVICE);
1376//        WallpaperInfo wi = wm.getWallpaperInfo();
1377//        if (wi != null && wi.getSettingsActivity() != null) {
1378//            LabeledIntent li = new LabeledIntent(getPackageName(),
1379//                    R.string.configure_wallpaper, 0);
1380//            li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
1381//            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
1382//        }
1383        startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
1384    }
1385
1386    /**
1387     * Registers various content observers. The current implementation registers
1388     * only a favorites observer to keep track of the favorites applications.
1389     */
1390    private void registerContentObservers() {
1391        ContentResolver resolver = getContentResolver();
1392        resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
1393                true, mWidgetObserver);
1394    }
1395
1396    @Override
1397    public boolean dispatchKeyEvent(KeyEvent event) {
1398        if (event.getAction() == KeyEvent.ACTION_DOWN) {
1399            switch (event.getKeyCode()) {
1400                case KeyEvent.KEYCODE_HOME:
1401                    return true;
1402                case KeyEvent.KEYCODE_VOLUME_DOWN:
1403                    if (SystemProperties.getInt("debug.launcher2.dumpstate", 0) != 0) {
1404                        dumpState();
1405                        return true;
1406                    }
1407                    break;
1408            }
1409        } else if (event.getAction() == KeyEvent.ACTION_UP) {
1410            switch (event.getKeyCode()) {
1411                case KeyEvent.KEYCODE_HOME:
1412                    return true;
1413            }
1414        }
1415
1416        return super.dispatchKeyEvent(event);
1417    }
1418
1419    @Override
1420    public void onBackPressed() {
1421        if (isAllAppsVisible()) {
1422            closeAllApps(true);
1423        } else {
1424            closeFolder();
1425        }
1426        dismissPreview(mPreviousView);
1427        dismissPreview(mNextView);
1428    }
1429
1430    private void closeFolder() {
1431        Folder folder = mWorkspace.getOpenFolder();
1432        if (folder != null) {
1433            closeFolder(folder);
1434        }
1435    }
1436
1437    void closeFolder(Folder folder) {
1438        folder.getInfo().opened = false;
1439        ViewGroup parent = (ViewGroup) folder.getParent();
1440        if (parent != null) {
1441            parent.removeView(folder);
1442            if (folder instanceof DropTarget) {
1443                // Live folders aren't DropTargets.
1444                mDragController.removeDropTarget((DropTarget)folder);
1445            }
1446        }
1447        folder.onClose();
1448    }
1449
1450    /**
1451     * Re-listen when widgets are reset.
1452     */
1453    private void onAppWidgetReset() {
1454        mAppWidgetHost.startListening();
1455    }
1456
1457    /**
1458     * Go through the and disconnect any of the callbacks in the drawables and the views or we
1459     * leak the previous Home screen on orientation change.
1460     */
1461    private void unbindDesktopItems() {
1462        for (ItemInfo item: mDesktopItems) {
1463            item.unbind();
1464        }
1465    }
1466
1467    /**
1468     * Launches the intent referred by the clicked shortcut.
1469     *
1470     * @param v The view representing the clicked shortcut.
1471     */
1472    public void onClick(View v) {
1473        Object tag = v.getTag();
1474        if (tag instanceof ShortcutInfo) {
1475            // Open shortcut
1476            final Intent intent = ((ShortcutInfo) tag).intent;
1477            int[] pos = new int[2];
1478            v.getLocationOnScreen(pos);
1479            intent.setSourceBounds(new Rect(pos[0], pos[1],
1480                    pos[0] + v.getWidth(), pos[1] + v.getHeight()));
1481            startActivitySafely(intent, tag);
1482        } else if (tag instanceof FolderInfo) {
1483            handleFolderClick((FolderInfo) tag);
1484        } else if (v == mHandleView) {
1485            if (isAllAppsVisible()) {
1486                closeAllApps(true);
1487            } else {
1488                showAllApps(true);
1489            }
1490        }
1491    }
1492
1493    void startActivitySafely(Intent intent, Object tag) {
1494        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1495        try {
1496            startActivity(intent);
1497        } catch (ActivityNotFoundException e) {
1498            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1499            Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
1500        } catch (SecurityException e) {
1501            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1502            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
1503                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1504                    "or use the exported attribute for this activity. "
1505                    + "tag="+ tag + " intent=" + intent, e);
1506        }
1507    }
1508
1509    void startActivityForResultSafely(Intent intent, int requestCode) {
1510        try {
1511            startActivityForResult(intent, requestCode);
1512        } catch (ActivityNotFoundException e) {
1513            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1514        } catch (SecurityException e) {
1515            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1516            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
1517                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1518                    "or use the exported attribute for this activity.", e);
1519        }
1520    }
1521
1522    private void handleFolderClick(FolderInfo folderInfo) {
1523        if (!folderInfo.opened) {
1524            // Close any open folder
1525            closeFolder();
1526            // Open the requested folder
1527            openFolder(folderInfo);
1528        } else {
1529            // Find the open folder...
1530            Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
1531            int folderScreen;
1532            if (openFolder != null) {
1533                folderScreen = mWorkspace.getScreenForView(openFolder);
1534                // .. and close it
1535                closeFolder(openFolder);
1536                if (folderScreen != mWorkspace.getCurrentScreen()) {
1537                    // Close any folder open on the current screen
1538                    closeFolder();
1539                    // Pull the folder onto this screen
1540                    openFolder(folderInfo);
1541                }
1542            }
1543        }
1544    }
1545
1546    /**
1547     * Opens the user fodler described by the specified tag. The opening of the folder
1548     * is animated relative to the specified View. If the View is null, no animation
1549     * is played.
1550     *
1551     * @param folderInfo The FolderInfo describing the folder to open.
1552     */
1553    private void openFolder(FolderInfo folderInfo) {
1554        Folder openFolder;
1555
1556        if (folderInfo instanceof UserFolderInfo) {
1557            openFolder = UserFolder.fromXml(this);
1558        } else if (folderInfo instanceof LiveFolderInfo) {
1559            openFolder = com.android.launcher2.LiveFolder.fromXml(this, folderInfo);
1560        } else {
1561            return;
1562        }
1563
1564        openFolder.setDragController(mDragController);
1565        openFolder.setLauncher(this);
1566
1567        openFolder.bind(folderInfo);
1568        folderInfo.opened = true;
1569
1570        mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4);
1571        openFolder.onOpen();
1572    }
1573
1574    public boolean onLongClick(View v) {
1575        switch (v.getId()) {
1576            case R.id.previous_screen:
1577                if (!isAllAppsVisible()) {
1578                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1579                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1580                    showPreviews(v);
1581                }
1582                return true;
1583            case R.id.next_screen:
1584                if (!isAllAppsVisible()) {
1585                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1586                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1587                    showPreviews(v);
1588                }
1589                return true;
1590            case R.id.all_apps_button:
1591                if (!isAllAppsVisible()) {
1592                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1593                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1594                    showPreviews(v);
1595                }
1596                return true;
1597        }
1598
1599        if (isWorkspaceLocked()) {
1600            return false;
1601        }
1602
1603        if (!(v instanceof CellLayout)) {
1604            v = (View) v.getParent();
1605        }
1606
1607        CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();
1608
1609        // This happens when long clicking an item with the dpad/trackball
1610        if (cellInfo == null) {
1611            return true;
1612        }
1613
1614        if (mWorkspace.allowLongPress()) {
1615            if (cellInfo.cell == null) {
1616                if (cellInfo.valid) {
1617                    // User long pressed on empty space
1618                    mWorkspace.setAllowLongPress(false);
1619                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1620                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1621                    showAddDialog(cellInfo);
1622                }
1623            } else {
1624                if (!(cellInfo.cell instanceof Folder)) {
1625                    // User long pressed on an item
1626                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1627                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1628                    mWorkspace.startDrag(cellInfo);
1629                }
1630            }
1631        }
1632        return true;
1633    }
1634
1635    @SuppressWarnings({"unchecked"})
1636    private void dismissPreview(final View v) {
1637        final PopupWindow window = (PopupWindow) v.getTag();
1638        if (window != null) {
1639            window.setOnDismissListener(new PopupWindow.OnDismissListener() {
1640                public void onDismiss() {
1641                    ViewGroup group = (ViewGroup) v.getTag(R.id.workspace);
1642                    int count = group.getChildCount();
1643                    for (int i = 0; i < count; i++) {
1644                        ((ImageView) group.getChildAt(i)).setImageDrawable(null);
1645                    }
1646                    ArrayList<Bitmap> bitmaps = (ArrayList<Bitmap>) v.getTag(R.id.icon);
1647                    for (Bitmap bitmap : bitmaps) bitmap.recycle();
1648
1649                    v.setTag(R.id.workspace, null);
1650                    v.setTag(R.id.icon, null);
1651                    window.setOnDismissListener(null);
1652                }
1653            });
1654            window.dismiss();
1655        }
1656        v.setTag(null);
1657    }
1658
1659    private void showPreviews(View anchor) {
1660        showPreviews(anchor, 0, mWorkspace.getChildCount());
1661    }
1662
1663    private void showPreviews(final View anchor, int start, int end) {
1664        final Resources resources = getResources();
1665        final Workspace workspace = mWorkspace;
1666
1667        CellLayout cell = ((CellLayout) workspace.getChildAt(start));
1668
1669        float max = workspace.getChildCount();
1670
1671        final Rect r = new Rect();
1672        resources.getDrawable(R.drawable.preview_background).getPadding(r);
1673        int extraW = (int) ((r.left + r.right) * max);
1674        int extraH = r.top + r.bottom;
1675
1676        int aW = cell.getWidth() - extraW;
1677        float w = aW / max;
1678
1679        int width = cell.getWidth();
1680        int height = cell.getHeight();
1681        int x = cell.getLeftPadding();
1682        int y = cell.getTopPadding();
1683        width -= (x + cell.getRightPadding());
1684        height -= (y + cell.getBottomPadding());
1685
1686        float scale = w / width;
1687
1688        int count = end - start;
1689
1690        final float sWidth = width * scale;
1691        float sHeight = height * scale;
1692
1693        LinearLayout preview = new LinearLayout(this);
1694
1695        PreviewTouchHandler handler = new PreviewTouchHandler(anchor);
1696        ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>(count);
1697
1698        for (int i = start; i < end; i++) {
1699            ImageView image = new ImageView(this);
1700            cell = (CellLayout) workspace.getChildAt(i);
1701
1702            final Bitmap bitmap = Bitmap.createBitmap((int) sWidth, (int) sHeight,
1703                    Bitmap.Config.ARGB_8888);
1704
1705            final Canvas c = new Canvas(bitmap);
1706            c.scale(scale, scale);
1707            c.translate(-cell.getLeftPadding(), -cell.getTopPadding());
1708            cell.dispatchDraw(c);
1709
1710            image.setBackgroundDrawable(resources.getDrawable(R.drawable.preview_background));
1711            image.setImageBitmap(bitmap);
1712            image.setTag(i);
1713            image.setOnClickListener(handler);
1714            image.setOnFocusChangeListener(handler);
1715            image.setFocusable(true);
1716            if (i == mWorkspace.getCurrentScreen()) image.requestFocus();
1717
1718            preview.addView(image,
1719                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
1720
1721            bitmaps.add(bitmap);
1722        }
1723
1724        final PopupWindow p = new PopupWindow(this);
1725        p.setContentView(preview);
1726        p.setWidth((int) (sWidth * count + extraW));
1727        p.setHeight((int) (sHeight + extraH));
1728        p.setAnimationStyle(R.style.AnimationPreview);
1729        p.setOutsideTouchable(true);
1730        p.setFocusable(true);
1731        p.setBackgroundDrawable(new ColorDrawable(0));
1732        p.showAsDropDown(anchor, 0, 0);
1733
1734        p.setOnDismissListener(new PopupWindow.OnDismissListener() {
1735            public void onDismiss() {
1736                dismissPreview(anchor);
1737            }
1738        });
1739
1740        anchor.setTag(p);
1741        anchor.setTag(R.id.workspace, preview);
1742        anchor.setTag(R.id.icon, bitmaps);
1743    }
1744
1745    class PreviewTouchHandler implements View.OnClickListener, Runnable, View.OnFocusChangeListener {
1746        private final View mAnchor;
1747
1748        public PreviewTouchHandler(View anchor) {
1749            mAnchor = anchor;
1750        }
1751
1752        public void onClick(View v) {
1753            mWorkspace.snapToScreen((Integer) v.getTag());
1754            v.post(this);
1755        }
1756
1757        public void run() {
1758            dismissPreview(mAnchor);
1759        }
1760
1761        public void onFocusChange(View v, boolean hasFocus) {
1762            if (hasFocus) {
1763                mWorkspace.snapToScreen((Integer) v.getTag());
1764            }
1765        }
1766    }
1767
1768    Workspace getWorkspace() {
1769        return mWorkspace;
1770    }
1771
1772    @Override
1773    protected Dialog onCreateDialog(int id) {
1774        switch (id) {
1775            case DIALOG_CREATE_SHORTCUT:
1776                return new CreateShortcut().createDialog();
1777            case DIALOG_RENAME_FOLDER:
1778                return new RenameFolder().createDialog();
1779        }
1780
1781        return super.onCreateDialog(id);
1782    }
1783
1784    @Override
1785    protected void onPrepareDialog(int id, Dialog dialog) {
1786        switch (id) {
1787            case DIALOG_CREATE_SHORTCUT:
1788                break;
1789            case DIALOG_RENAME_FOLDER:
1790                if (mFolderInfo != null) {
1791                    EditText input = (EditText) dialog.findViewById(R.id.folder_name);
1792                    final CharSequence text = mFolderInfo.title;
1793                    input.setText(text);
1794                    input.setSelection(0, text.length());
1795                }
1796                break;
1797        }
1798    }
1799
1800    void showRenameDialog(FolderInfo info) {
1801        mFolderInfo = info;
1802        mWaitingForResult = true;
1803        showDialog(DIALOG_RENAME_FOLDER);
1804    }
1805
1806    private void showAddDialog(CellLayout.CellInfo cellInfo) {
1807        mAddItemCellInfo = cellInfo;
1808        mWaitingForResult = true;
1809        showDialog(DIALOG_CREATE_SHORTCUT);
1810    }
1811
1812    private void pickShortcut() {
1813        Bundle bundle = new Bundle();
1814
1815        ArrayList<String> shortcutNames = new ArrayList<String>();
1816        shortcutNames.add(getString(R.string.group_applications));
1817        bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
1818
1819        ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>();
1820        shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
1821                        R.drawable.ic_launcher_application));
1822        bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
1823
1824        Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1825        pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(Intent.ACTION_CREATE_SHORTCUT));
1826        pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_shortcut));
1827        pickIntent.putExtras(bundle);
1828
1829        startActivityForResult(pickIntent, REQUEST_PICK_SHORTCUT);
1830    }
1831
1832    private class RenameFolder {
1833        private EditText mInput;
1834
1835        Dialog createDialog() {
1836            final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
1837            mInput = (EditText) layout.findViewById(R.id.folder_name);
1838
1839            AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1840            builder.setIcon(0);
1841            builder.setTitle(getString(R.string.rename_folder_title));
1842            builder.setCancelable(true);
1843            builder.setOnCancelListener(new Dialog.OnCancelListener() {
1844                public void onCancel(DialogInterface dialog) {
1845                    cleanup();
1846                }
1847            });
1848            builder.setNegativeButton(getString(R.string.cancel_action),
1849                new Dialog.OnClickListener() {
1850                    public void onClick(DialogInterface dialog, int which) {
1851                        cleanup();
1852                    }
1853                }
1854            );
1855            builder.setPositiveButton(getString(R.string.rename_action),
1856                new Dialog.OnClickListener() {
1857                    public void onClick(DialogInterface dialog, int which) {
1858                        changeFolderName();
1859                    }
1860                }
1861            );
1862            builder.setView(layout);
1863
1864            final AlertDialog dialog = builder.create();
1865            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
1866                public void onShow(DialogInterface dialog) {
1867                    mWaitingForResult = true;
1868                    mInput.requestFocus();
1869                    InputMethodManager inputManager = (InputMethodManager)
1870                            getSystemService(Context.INPUT_METHOD_SERVICE);
1871                    inputManager.showSoftInput(mInput, 0);
1872                }
1873            });
1874
1875            return dialog;
1876        }
1877
1878        private void changeFolderName() {
1879            final String name = mInput.getText().toString();
1880            if (!TextUtils.isEmpty(name)) {
1881                // Make sure we have the right folder info
1882                mFolderInfo = sFolders.get(mFolderInfo.id);
1883                mFolderInfo.title = name;
1884                LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
1885
1886                if (mWorkspaceLoading) {
1887                    lockAllApps();
1888                    mModel.startLoader(Launcher.this, false);
1889                } else {
1890                    final FolderIcon folderIcon = (FolderIcon)
1891                            mWorkspace.getViewForTag(mFolderInfo);
1892                    if (folderIcon != null) {
1893                        folderIcon.setText(name);
1894                        getWorkspace().requestLayout();
1895                    } else {
1896                        lockAllApps();
1897                        mWorkspaceLoading = true;
1898                        mModel.startLoader(Launcher.this, false);
1899                    }
1900                }
1901            }
1902            cleanup();
1903        }
1904
1905        private void cleanup() {
1906            dismissDialog(DIALOG_RENAME_FOLDER);
1907            mWaitingForResult = false;
1908            mFolderInfo = null;
1909        }
1910    }
1911
1912    // Now a part of LauncherModel.Callbacks. Used to reorder loading steps.
1913    public boolean isAllAppsVisible() {
1914        return (mAllAppsGrid != null) ? mAllAppsGrid.isVisible() : false;
1915    }
1916
1917    // AllAppsView.Watcher
1918    public void zoomed(float zoom) {
1919        if (zoom == 1.0f) {
1920            mWorkspace.setVisibility(View.GONE);
1921        }
1922    }
1923
1924    void showAllApps(boolean animated) {
1925        mAllAppsGrid.zoom(1.0f, animated);
1926
1927        ((View) mAllAppsGrid).setFocusable(true);
1928        ((View) mAllAppsGrid).requestFocus();
1929
1930        // TODO: fade these two too
1931        mDeleteZone.setVisibility(View.GONE);
1932    }
1933
1934    /**
1935     * Things to test when changing this code.
1936     *   - Home from workspace
1937     *          - from center screen
1938     *          - from other screens
1939     *   - Home from all apps
1940     *          - from center screen
1941     *          - from other screens
1942     *   - Back from all apps
1943     *          - from center screen
1944     *          - from other screens
1945     *   - Launch app from workspace and quit
1946     *          - with back
1947     *          - with home
1948     *   - Launch app from all apps and quit
1949     *          - with back
1950     *          - with home
1951     *   - Go to a screen that's not the default, then all
1952     *     apps, and launch and app, and go back
1953     *          - with back
1954     *          -with home
1955     *   - On workspace, long press power and go back
1956     *          - with back
1957     *          - with home
1958     *   - On all apps, long press power and go back
1959     *          - with back
1960     *          - with home
1961     *   - On workspace, power off
1962     *   - On all apps, power off
1963     *   - Launch an app and turn off the screen while in that app
1964     *          - Go back with home key
1965     *          - Go back with back key  TODO: make this not go to workspace
1966     *          - From all apps
1967     *          - From workspace
1968     *   - Enter and exit car mode (becuase it causes an extra configuration changed)
1969     *          - From all apps
1970     *          - From the center workspace
1971     *          - From another workspace
1972     */
1973    void closeAllApps(boolean animated) {
1974        if (mAllAppsGrid.isVisible()) {
1975            mWorkspace.setVisibility(View.VISIBLE);
1976            mAllAppsGrid.zoom(0.0f, animated);
1977            ((View)mAllAppsGrid).setFocusable(false);
1978            mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1979        }
1980    }
1981
1982    void lockAllApps() {
1983        // TODO
1984    }
1985
1986    void unlockAllApps() {
1987        // TODO
1988    }
1989
1990    /**
1991     * Displays the shortcut creation dialog and launches, if necessary, the
1992     * appropriate activity.
1993     */
1994    private class CreateShortcut implements DialogInterface.OnClickListener,
1995            DialogInterface.OnCancelListener, DialogInterface.OnDismissListener,
1996            DialogInterface.OnShowListener {
1997
1998        private AddAdapter mAdapter;
1999
2000        Dialog createDialog() {
2001            mAdapter = new AddAdapter(Launcher.this);
2002
2003            final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
2004            builder.setTitle(getString(R.string.menu_item_add_item));
2005            builder.setAdapter(mAdapter, this);
2006
2007            builder.setInverseBackgroundForced(true);
2008
2009            AlertDialog dialog = builder.create();
2010            dialog.setOnCancelListener(this);
2011            dialog.setOnDismissListener(this);
2012            dialog.setOnShowListener(this);
2013
2014            return dialog;
2015        }
2016
2017        public void onCancel(DialogInterface dialog) {
2018            mWaitingForResult = false;
2019            cleanup();
2020        }
2021
2022        public void onDismiss(DialogInterface dialog) {
2023        }
2024
2025        private void cleanup() {
2026            try {
2027                dismissDialog(DIALOG_CREATE_SHORTCUT);
2028            } catch (Exception e) {
2029                // An exception is thrown if the dialog is not visible, which is fine
2030            }
2031        }
2032
2033        /**
2034         * Handle the action clicked in the "Add to home" dialog.
2035         */
2036        public void onClick(DialogInterface dialog, int which) {
2037            Resources res = getResources();
2038            cleanup();
2039
2040            switch (which) {
2041                case AddAdapter.ITEM_SHORTCUT: {
2042                    // Insert extra item to handle picking application
2043                    pickShortcut();
2044                    break;
2045                }
2046
2047                case AddAdapter.ITEM_APPWIDGET: {
2048                    int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId();
2049
2050                    Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
2051                    pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
2052                    // start the pick activity
2053                    startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
2054                    break;
2055                }
2056
2057                case AddAdapter.ITEM_LIVE_FOLDER: {
2058                    // Insert extra item to handle inserting folder
2059                    Bundle bundle = new Bundle();
2060
2061                    ArrayList<String> shortcutNames = new ArrayList<String>();
2062                    shortcutNames.add(res.getString(R.string.group_folder));
2063                    bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
2064
2065                    ArrayList<ShortcutIconResource> shortcutIcons =
2066                            new ArrayList<ShortcutIconResource>();
2067                    shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
2068                            R.drawable.ic_launcher_folder));
2069                    bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
2070
2071                    Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
2072                    pickIntent.putExtra(Intent.EXTRA_INTENT,
2073                            new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER));
2074                    pickIntent.putExtra(Intent.EXTRA_TITLE,
2075                            getText(R.string.title_select_live_folder));
2076                    pickIntent.putExtras(bundle);
2077
2078                    startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);
2079                    break;
2080                }
2081
2082                case AddAdapter.ITEM_WALLPAPER: {
2083                    startWallpaper();
2084                    break;
2085                }
2086            }
2087        }
2088
2089        public void onShow(DialogInterface dialog) {
2090            mWaitingForResult = true;
2091        }
2092    }
2093
2094    /**
2095     * Receives notifications when applications are added/removed.
2096     */
2097    private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
2098        @Override
2099        public void onReceive(Context context, Intent intent) {
2100            closeSystemDialogs();
2101            String reason = intent.getStringExtra("reason");
2102            if (!"homekey".equals(reason)) {
2103                boolean animate = true;
2104                if (mPaused || "lock".equals(reason)) {
2105                    animate = false;
2106                }
2107                closeAllApps(animate);
2108            }
2109        }
2110    }
2111
2112    /**
2113     * Receives notifications whenever the appwidgets are reset.
2114     */
2115    private class AppWidgetResetObserver extends ContentObserver {
2116        public AppWidgetResetObserver() {
2117            super(new Handler());
2118        }
2119
2120        @Override
2121        public void onChange(boolean selfChange) {
2122            onAppWidgetReset();
2123        }
2124    }
2125
2126    /**
2127     * Implementation of the method from LauncherModel.Callbacks.
2128     */
2129    public int getCurrentWorkspaceScreen() {
2130        if (mWorkspace != null) {
2131            return mWorkspace.getCurrentScreen();
2132        } else {
2133            return SCREEN_COUNT / 2;
2134        }
2135    }
2136
2137    /**
2138     * Refreshes the shortcuts shown on the workspace.
2139     *
2140     * Implementation of the method from LauncherModel.Callbacks.
2141     */
2142    public void startBinding() {
2143        final Workspace workspace = mWorkspace;
2144        int count = workspace.getChildCount();
2145        for (int i = 0; i < count; i++) {
2146            // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
2147            ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
2148        }
2149
2150        if (DEBUG_USER_INTERFACE) {
2151            android.widget.Button finishButton = new android.widget.Button(this);
2152            finishButton.setText("Finish");
2153            workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
2154
2155            finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
2156                public void onClick(View v) {
2157                    finish();
2158                }
2159            });
2160        }
2161    }
2162
2163    /**
2164     * Bind the items start-end from the list.
2165     *
2166     * Implementation of the method from LauncherModel.Callbacks.
2167     */
2168    public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
2169
2170        final Workspace workspace = mWorkspace;
2171
2172        for (int i=start; i<end; i++) {
2173            final ItemInfo item = shortcuts.get(i);
2174            mDesktopItems.add(item);
2175            switch (item.itemType) {
2176                case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2177                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2178                    final View shortcut = createShortcut((ShortcutInfo)item);
2179                    workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
2180                            false);
2181                    break;
2182                case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
2183                    final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
2184                            (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
2185                            (UserFolderInfo) item);
2186                    workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
2187                            false);
2188                    break;
2189                case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
2190                    final FolderIcon newLiveFolder = LiveFolderIcon.fromXml(
2191                            R.layout.live_folder_icon, this,
2192                            (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
2193                            (LiveFolderInfo) item);
2194                    workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1,
2195                            false);
2196                    break;
2197            }
2198        }
2199
2200        workspace.requestLayout();
2201    }
2202
2203    /**
2204     * Implementation of the method from LauncherModel.Callbacks.
2205     */
2206    public void bindFolders(HashMap<Long, FolderInfo> folders) {
2207        sFolders.clear();
2208        sFolders.putAll(folders);
2209    }
2210
2211    /**
2212     * Add the views for a widget to the workspace.
2213     *
2214     * Implementation of the method from LauncherModel.Callbacks.
2215     */
2216    public void bindAppWidget(LauncherAppWidgetInfo item) {
2217        final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
2218        if (DEBUG_WIDGETS) {
2219            Log.d(TAG, "bindAppWidget: " + item);
2220        }
2221        final Workspace workspace = mWorkspace;
2222
2223        final int appWidgetId = item.appWidgetId;
2224        final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
2225        if (DEBUG_WIDGETS) {
2226            Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
2227        }
2228
2229        item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
2230
2231        item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
2232        item.hostView.setTag(item);
2233
2234        workspace.addInScreen(item.hostView, item.screen, item.cellX,
2235                item.cellY, item.spanX, item.spanY, false);
2236
2237        workspace.requestLayout();
2238
2239        mDesktopItems.add(item);
2240
2241        if (DEBUG_WIDGETS) {
2242            Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
2243                    + (SystemClock.uptimeMillis()-start) + "ms");
2244        }
2245    }
2246
2247    /**
2248     * Callback saying that there aren't any more items to bind.
2249     *
2250     * Implementation of the method from LauncherModel.Callbacks.
2251     */
2252    public void finishBindingItems() {
2253        if (mSavedState != null) {
2254            if (!mWorkspace.hasFocus()) {
2255                mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
2256            }
2257
2258            final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);
2259            if (userFolders != null) {
2260                for (long folderId : userFolders) {
2261                    final FolderInfo info = sFolders.get(folderId);
2262                    if (info != null) {
2263                        openFolder(info);
2264                    }
2265                }
2266                final Folder openFolder = mWorkspace.getOpenFolder();
2267                if (openFolder != null) {
2268                    openFolder.requestFocus();
2269                }
2270            }
2271
2272            mSavedState = null;
2273        }
2274
2275        if (mSavedInstanceState != null) {
2276            super.onRestoreInstanceState(mSavedInstanceState);
2277            mSavedInstanceState = null;
2278        }
2279
2280        mWorkspaceLoading = false;
2281    }
2282
2283    /**
2284     * Add the icons for all apps.
2285     *
2286     * Implementation of the method from LauncherModel.Callbacks.
2287     */
2288    public void bindAllApplications(ArrayList<ApplicationInfo> apps) {
2289        mAllAppsGrid.setApps(apps);
2290    }
2291
2292    /**
2293     * A package was installed.
2294     *
2295     * Implementation of the method from LauncherModel.Callbacks.
2296     */
2297    public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {
2298        removeDialog(DIALOG_CREATE_SHORTCUT);
2299        mAllAppsGrid.addApps(apps);
2300    }
2301
2302    /**
2303     * A package was updated.
2304     *
2305     * Implementation of the method from LauncherModel.Callbacks.
2306     */
2307    public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) {
2308        removeDialog(DIALOG_CREATE_SHORTCUT);
2309        mWorkspace.updateShortcuts(apps);
2310        mAllAppsGrid.updateApps(apps);
2311    }
2312
2313    /**
2314     * A package was uninstalled.
2315     *
2316     * Implementation of the method from LauncherModel.Callbacks.
2317     */
2318    public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent) {
2319        removeDialog(DIALOG_CREATE_SHORTCUT);
2320        if (permanent) {
2321            mWorkspace.removeItems(apps);
2322        }
2323        mAllAppsGrid.removeApps(apps);
2324    }
2325
2326    /**
2327     * Prints out out state for debugging.
2328     */
2329    public void dumpState() {
2330        Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this);
2331        Log.d(TAG, "mSavedState=" + mSavedState);
2332        Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
2333        Log.d(TAG, "mRestoring=" + mRestoring);
2334        Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
2335        Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
2336        Log.d(TAG, "mDesktopItems.size=" + mDesktopItems.size());
2337        Log.d(TAG, "sFolders.size=" + sFolders.size());
2338        mModel.dumpState();
2339        mAllAppsGrid.dumpState();
2340        Log.d(TAG, "END launcher2 dump state");
2341    }
2342}
2343