blob: 928f4caecde593d0fb430718de28d5e52df989ad [file] [log] [blame]
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001/*
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.launcher;
18
19import android.app.Activity;
20import android.app.AlertDialog;
21import android.app.Application;
22import android.app.Dialog;
23import android.app.SearchManager;
24import android.app.StatusBarManager;
25import android.content.ActivityNotFoundException;
26import android.content.BroadcastReceiver;
27import android.content.ContentResolver;
28import android.content.Context;
29import android.content.DialogInterface;
30import android.content.Intent;
31import android.content.IntentFilter;
The Android Open Source Projectd097a182008-12-17 18:05:58 -080032import android.content.SharedPreferences;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -070033import android.content.pm.PackageManager;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -070034import android.content.res.Resources;
The Android Open Source Projectd097a182008-12-17 18:05:58 -080035import android.content.res.Configuration;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -070036import android.database.ContentObserver;
37import android.graphics.Bitmap;
38import android.graphics.drawable.BitmapDrawable;
39import android.graphics.drawable.Drawable;
40import android.graphics.drawable.TransitionDrawable;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -070041import android.net.Uri;
42import android.os.Bundle;
43import android.os.Handler;
44import android.os.IBinder;
45import android.os.Parcelable;
46import android.os.RemoteException;
47import android.os.ServiceManager;
The Android Open Source Projectd097a182008-12-17 18:05:58 -080048import android.provider.*;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -070049import android.telephony.PhoneNumberUtils;
50import android.text.Selection;
51import android.text.SpannableStringBuilder;
52import android.text.TextUtils;
53import android.text.method.TextKeyListener;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -070054import android.util.Log;
55import android.view.Display;
56import android.view.Gravity;
57import android.view.KeyEvent;
58import android.view.LayoutInflater;
59import android.view.Menu;
60import android.view.MenuItem;
61import android.view.View;
62import android.view.ViewGroup;
63import android.view.WindowManager;
64import android.view.View.OnLongClickListener;
The Android Open Source Projectd097a182008-12-17 18:05:58 -080065import android.view.inputmethod.InputMethodManager;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -070066import android.widget.EditText;
67import android.widget.ExpandableListView;
68import android.widget.ImageView;
69import android.widget.TextView;
70import android.widget.Toast;
The Android Open Source Projectd097a182008-12-17 18:05:58 -080071import android.widget.GridView;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -070072import android.app.IWallpaperService;
73
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -070074import com.android.internal.widget.SlidingDrawer;
75
76import java.lang.ref.WeakReference;
77import java.util.ArrayList;
78
79/**
80 * Default launcher application.
81 */
82public final class Launcher extends Activity implements View.OnClickListener, OnLongClickListener {
83 static final String LOG_TAG = "Launcher";
84
85 private static final boolean PROFILE_STARTUP = false;
86 private static final boolean DEBUG_USER_INTERFACE = false;
87
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -070088 private static final boolean REMOVE_SHORTCUT_ON_PACKAGE_REMOVE = false;
89
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -070090 private static final int WALLPAPER_SCREENS_SPAN = 2;
91
92 private static final int MENU_GROUP_ADD = 1;
93 private static final int MENU_ADD = Menu.FIRST + 1;
94 private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1;
95 private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1;
96 private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1;
97 private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1;
98
99 private static final int REQUEST_CREATE_SHORTCUT = 1;
100 private static final int REQUEST_CHOOSE_PHOTO = 2;
101 private static final int REQUEST_UPDATE_PHOTO = 3;
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800102 private static final int REQUEST_CREATE_LIVE_FOLDER = 4;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700103
104 static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
105
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800106 static final int SCREEN_COUNT = 3;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700107 static final int DEFAULT_SCREN = 1;
108 static final int NUMBER_CELLS_X = 4;
109 static final int NUMBER_CELLS_Y = 4;
110
111 private static final int DIALOG_CREATE_SHORTCUT = 1;
112 static final int DIALOG_RENAME_FOLDER = 2;
113
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800114 private static final String PREFERENCES = "launcher";
115 private static final String KEY_LOCALE = "locale";
116 private static final String KEY_MCC = "mcc";
117 private static final String KEY_MNC = "mnc";
118
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700119 // Type: int
120 private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
121 // Type: boolean
122 private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder";
123 // Type: long
124 private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder";
125 // Type: int
126 private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
127 // Type: int
128 private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX";
129 // Type: int
130 private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY";
131 // Type: int
132 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX";
133 // Type: int
134 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY";
135 // Type: int
136 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX";
137 // Type: int
138 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY";
139 // Type: int[]
140 private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells";
141 // Type: boolean
142 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
143 // Type: long
144 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
145
146 private static LauncherModel sModel;
147
148 private static Bitmap sWallpaper;
149
150 // Indicates whether the OpenGL pipeline was enabled, either through
151 // USE_OPENGL_BY_DEFAULT or the system property launcher.opengl
152 static boolean sOpenGlEnabled;
153
154 private static final Object sLock = new Object();
155 private static int sScreen = DEFAULT_SCREN;
156
157 private static WallpaperIntentReceiver sWallpaperReceiver;
158
159 private final BroadcastReceiver mApplicationsReceiver = new ApplicationsIntentReceiver();
160 private final ContentObserver mObserver = new FavoritesChangeObserver();
161
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700162 private LayoutInflater mInflater;
163
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700164 private DragLayer mDragLayer;
165 private Workspace mWorkspace;
166
167 private CellLayout.CellInfo mAddItemCellInfo;
168 private CellLayout.CellInfo mMenuAddInfo;
169 private final int[] mCellCoordinates = new int[2];
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800170 private FolderInfo mFolderInfo;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700171
172 private SlidingDrawer mDrawer;
173 private TransitionDrawable mHandleIcon;
174 private AllAppsGridView mAllAppsGrid;
175
176 private boolean mDesktopLocked = true;
177 private Bundle mSavedState;
178
179 private SpannableStringBuilder mDefaultKeySsb = null;
180
181 private boolean mDestroyed;
182
183 private boolean mRestoring;
184 private boolean mWaitingForResult;
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800185 private boolean mLocaleChanged;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700186
187 @Override
188 protected void onCreate(Bundle savedInstanceState) {
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700189 super.onCreate(savedInstanceState);
190 mInflater = getLayoutInflater();
191
192 if (PROFILE_STARTUP) {
193 android.os.Debug.startMethodTracing("/sdcard/launcher");
194 }
195
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800196 checkForLocaleChange();
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700197 setWallpaperDimension();
198
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700199 if (sModel == null) {
200 sModel = new LauncherModel();
201 }
202
203 setContentView(R.layout.launcher);
204 setupViews();
205
206 registerIntentReceivers();
207 registerContentObservers();
208
209 mSavedState = savedInstanceState;
210 restoreState(mSavedState);
211
212 if (PROFILE_STARTUP) {
213 android.os.Debug.stopMethodTracing();
214 }
215
216 if (!mRestoring) {
217 startLoaders();
218 }
219
220 // For handling default keys
221 mDefaultKeySsb = new SpannableStringBuilder();
222 Selection.setSelection(mDefaultKeySsb, 0);
223 }
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800224
225 private void checkForLocaleChange() {
226 final SharedPreferences preferences = getSharedPreferences(PREFERENCES, MODE_PRIVATE);
227 final Configuration configuration = getResources().getConfiguration();
228
229 final String previousLocale = preferences.getString(KEY_LOCALE, null);
230 final String locale = configuration.locale.toString();
231
232 final int previousMcc = preferences.getInt(KEY_MCC, -1);
233 final int mcc = configuration.mcc;
234
235 final int previousMnc = preferences.getInt(KEY_MNC, -1);
236 final int mnc = configuration.mnc;
237
238 mLocaleChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
239
240 if (mLocaleChanged) {
241 final SharedPreferences.Editor editor = preferences.edit();
242 editor.putString(KEY_LOCALE, locale);
243 editor.putInt(KEY_MCC, mcc);
244 editor.putInt(KEY_MNC, mnc);
245 editor.commit();
246 }
247 }
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700248
249 static int getScreen() {
250 synchronized (sLock) {
251 return sScreen;
252 }
253 }
254
255 static void setScreen(int screen) {
256 synchronized (sLock) {
257 sScreen = screen;
258 }
259 }
260
261 private void startLoaders() {
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800262 sModel.loadApplications(true, this, mLocaleChanged);
263 sModel.loadUserItems(!mLocaleChanged, this, mLocaleChanged);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700264 mRestoring = false;
265 }
266
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700267 private void setWallpaperDimension() {
268 IBinder binder = ServiceManager.getService(WALLPAPER_SERVICE);
269 IWallpaperService wallpaperService = IWallpaperService.Stub.asInterface(binder);
270
271 Display display = getWindowManager().getDefaultDisplay();
272 boolean isPortrait = display.getWidth() < display.getHeight();
273
274 final int width = isPortrait ? display.getWidth() : display.getHeight();
275 final int height = isPortrait ? display.getHeight() : display.getWidth();
276 try {
277 wallpaperService.setDimensionHints(width * WALLPAPER_SCREENS_SPAN, height);
278 } catch (RemoteException e) {
279 // System is dead!
280 }
281 }
282
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700283 @Override
284 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
285 if (resultCode == RESULT_OK && mAddItemCellInfo != null) {
286 switch (requestCode) {
287 case REQUEST_CREATE_SHORTCUT:
288 completeAddShortcut(data, mAddItemCellInfo, !mDesktopLocked);
289 break;
290 case REQUEST_CHOOSE_PHOTO:
291 completeAddPhotoFrame(data, mAddItemCellInfo);
292 break;
293 case REQUEST_UPDATE_PHOTO:
294 completeUpdatePhotoFrame(data, mAddItemCellInfo);
295 break;
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800296 case REQUEST_CREATE_LIVE_FOLDER:
297 completeAddLiveFolder(data, mAddItemCellInfo, !mDesktopLocked);
298 break;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700299 }
300 }
301 mWaitingForResult = false;
302 }
303
304 @Override
305 protected void onResume() {
306 super.onResume();
307
308 if (mRestoring) {
309 startLoaders();
310 }
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700311 }
312
313 @Override
314 public boolean onKeyUp(int keyCode, KeyEvent event) {
315 boolean handled = super.onKeyUp(keyCode, event);
316 if (keyCode == KeyEvent.KEYCODE_SEARCH) {
317 handled = mWorkspace.snapToSearch();
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800318 if (handled) closeDrawer(true);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700319 }
320 return handled;
321 }
322
323 @Override
324 public boolean onKeyDown(int keyCode, KeyEvent event) {
325 boolean handled = super.onKeyDown(keyCode, event);
326 if (!handled && keyCode != KeyEvent.KEYCODE_ENTER) {
327 boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
328 keyCode, event);
329 if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
330 // something usable has been typed - dispatch it now.
331 final String str = mDefaultKeySsb.toString();
332
333 boolean isDialable = true;
334 final int count = str.length();
335 for (int i = 0; i < count; i++) {
336 if (!PhoneNumberUtils.isReallyDialable(str.charAt(i))) {
337 isDialable = false;
338 break;
339 }
340 }
341 Intent intent;
342 if (isDialable) {
343 intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", str, null));
344 } else {
345 intent = new Intent(Contacts.Intents.UI.FILTER_CONTACTS_ACTION);
346 intent.putExtra(Contacts.Intents.UI.FILTER_TEXT_EXTRA_KEY, str);
347 }
348
349 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
350
351 try {
352 startActivity(intent);
353 } catch (android.content.ActivityNotFoundException ex) {
354 // Oh well... no one knows how to filter/dial. Life goes on.
355 }
356
357 mDefaultKeySsb.clear();
358 mDefaultKeySsb.clearSpans();
359 Selection.setSelection(mDefaultKeySsb, 0);
360
361 return true;
362 }
363 }
364
365 return handled;
366 }
367
368 /**
369 * Restores the previous state, if it exists.
370 *
371 * @param savedState The previous state.
372 */
373 private void restoreState(Bundle savedState) {
374 if (savedState == null) {
375 return;
376 }
377
378 final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
379 if (currentScreen > -1) {
380 mWorkspace.setCurrentScreen(currentScreen);
381 }
382
383 final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
384 if (addScreen > -1) {
385 mAddItemCellInfo = new CellLayout.CellInfo();
386 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
387 addItemCellInfo.valid = true;
388 addItemCellInfo.screen = addScreen;
389 addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
390 addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
391 addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
392 addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
393 addItemCellInfo.findVacantCellsFromOccupied(
394 savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
395 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
396 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
397 mRestoring = true;
398 }
399
400
401 boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
402 if (renameFolder) {
403 long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
404 mFolderInfo = sModel.getFolderById(this, id);
405 mRestoring = true;
406 }
407 }
408
409 /**
410 * Finds all the views we need and configure them properly.
411 */
412 private void setupViews() {
413 mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
414 final DragLayer dragLayer = mDragLayer;
415
416 mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
417 final Workspace workspace = mWorkspace;
418
419 mDrawer = (SlidingDrawer) dragLayer.findViewById(R.id.drawer);
420 final SlidingDrawer drawer = mDrawer;
421
422 mAllAppsGrid = (AllAppsGridView) drawer.getContent();
423 final AllAppsGridView grid = mAllAppsGrid;
424
425 final DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone);
426
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800427 final HandleView handleIcon = (HandleView) drawer.findViewById(R.id.all_apps);
428 handleIcon.setLauncher(this);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700429 mHandleIcon = (TransitionDrawable) handleIcon.getDrawable();
430 mHandleIcon.setCrossFadeEnabled(true);
431
432 drawer.lock();
433 final DrawerManager drawerManager = new DrawerManager();
434 drawer.setOnDrawerOpenListener(drawerManager);
435 drawer.setOnDrawerCloseListener(drawerManager);
436 drawer.setOnDrawerScrollListener(drawerManager);
437
438 grid.setTextFilterEnabled(true);
439 grid.setDragger(dragLayer);
440 grid.setLauncher(this);
441 if (sOpenGlEnabled) {
442 grid.setScrollingCacheEnabled(false);
443 grid.setFadingEdgeLength(0);
444 }
445
446 workspace.setOnLongClickListener(this);
447 workspace.setDragger(dragLayer);
448 workspace.setLauncher(this);
449 loadWallpaper();
450
451 deleteZone.setLauncher(this);
452 deleteZone.setDragController(dragLayer);
453 deleteZone.setHandle(handleIcon);
454
455 dragLayer.setIgnoredDropTarget(grid);
456 dragLayer.setDragScoller(workspace);
457 dragLayer.setDragListener(deleteZone);
458
459 if (DEBUG_USER_INTERFACE) {
460 android.widget.Button finishButton = new android.widget.Button(this);
461 finishButton.setText("Finish");
462 workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
463
464 finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
465 public void onClick(View v) {
466 finish();
467 }
468 });
469 }
470 }
471
472 /**
473 * Creates a view representing a shortcut.
474 *
475 * @param info The data structure describing the shortcut.
476 *
477 * @return A View inflated from R.layout.application.
478 */
479 View createShortcut(ApplicationInfo info) {
480 return createShortcut(R.layout.application,
481 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
482 }
483
484 /**
485 * Creates a view representing a shortcut inflated from the specified resource.
486 *
487 * @param layoutResId The id of the XML layout used to create the shortcut.
488 * @param parent The group the shortcut belongs to.
489 * @param info The data structure describing the shortcut.
490 *
491 * @return A View inflated from layoutResId.
492 */
493 View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) {
494 TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false);
495
496 if (!info.filtered) {
497 info.icon = Utilities.createIconThumbnail(info.icon, this);
498 info.filtered = true;
499 }
500
501 favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null);
502 favorite.setText(info.title);
503 favorite.setTag(info);
504 favorite.setOnClickListener(this);
505
506 return favorite;
507 }
508
509 void addApplicationShortcut(ApplicationInfo info) {
510 mAddItemCellInfo.screen = mWorkspace.getCurrentScreen();
511 mWorkspace.addApplicationShortcut(info, mAddItemCellInfo);
512 }
513
514 /**
515 * Add a shortcut to the workspace.
516 *
517 * @param data The intent describing the shortcut.
518 * @param cellInfo The position on screen where to create the shortcut.
519 * @param insertAtFirst
520 */
521 private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo,
522 boolean insertAtFirst) {
523
524 cellInfo.screen = mWorkspace.getCurrentScreen();
525 final ApplicationInfo info = addShortcut(this, data, cellInfo, false);
526
527 if (!mRestoring) {
528 sModel.addDesktopItem(info);
529
530 final View view = createShortcut(info);
531 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
532 } else if (sModel.isDesktopLoaded()) {
533 sModel.addDesktopItem(info);
534 }
535 }
536
537 static ApplicationInfo addShortcut(Context context, Intent data,
538 CellLayout.CellInfo cellInfo, boolean notify) {
539
540 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
541 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
542 Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
543
544 Drawable icon = null;
545 boolean filtered = false;
546 boolean customIcon = false;
547 Intent.ShortcutIconResource iconResource = null;
548
549 if (bitmap != null) {
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800550 icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context));
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700551 filtered = true;
552 customIcon = true;
553 } else {
554 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
555 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
556 try {
557 iconResource = (Intent.ShortcutIconResource) extra;
558 final PackageManager packageManager = context.getPackageManager();
559 Resources resources = packageManager.getResourcesForApplication(
560 iconResource.packageName);
561 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
562 icon = resources.getDrawable(id);
563 } catch (Exception e) {
564 Log.w(LOG_TAG, "Could not load shortcut icon: " + extra);
565 }
566 }
567 }
568
569 if (icon == null) {
570 icon = context.getPackageManager().getDefaultActivityIcon();
571 }
572
573 final ApplicationInfo info = new ApplicationInfo();
574 info.icon = icon;
575 info.filtered = filtered;
576 info.title = name;
577 info.intent = intent;
578 info.customIcon = customIcon;
579 info.iconResource = iconResource;
580
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800581 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700582 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
583 return info;
584 }
585
586 /**
587 * Add a PhotFrame to the workspace.
588 *
589 * @param data The intent describing the photo.
590 * @param cellInfo The position on screen where to create the shortcut.
591 */
592 private void completeAddPhotoFrame(Intent data, CellLayout.CellInfo cellInfo) {
593 final Bundle extras = data.getExtras();
594 if (extras != null) {
595 Bitmap photo = extras.getParcelable("data");
596
597 Widget info = Widget.makePhotoFrame();
598 info.photo = photo;
599
600 final int[] xy = mCellCoordinates;
601 if (!findSlot(cellInfo, xy, info.spanX, info.spanY)) return;
602
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800603 LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700604 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
605
606 if (!mRestoring) {
607 sModel.addDesktopItem(info);
608
609 final PhotoFrame view = (PhotoFrame) mInflater.inflate(info.layoutResource, null);
610 view.setImageBitmap(photo);
611 view.setTag(info);
612
613 mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, info.spanY);
614 } else if (sModel.isDesktopLoaded()) {
615 sModel.addDesktopItem(info);
616 }
617 }
618 }
619
620 /**
621 * Updates a workspace PhotoFrame.
622 *
623 * @param data The intent describing the photo.
624 * @param cellInfo The position on screen of the PhotoFrame to update.
625 */
626 private void completeUpdatePhotoFrame(Intent data, CellLayout.CellInfo cellInfo) {
627 final Bundle extras = data.getExtras();
628 if (extras != null) {
629 Widget info;
630 Bitmap photo = extras.getParcelable("data");
631
632 if (!mRestoring) {
633 final CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen);
634 final PhotoFrame view = (PhotoFrame) layout.findCell(cellInfo.cellX, cellInfo.cellY,
635 cellInfo.spanX, cellInfo.spanY, null);
636 view.setImageBitmap(photo);
637 info = (Widget) view.getTag();
638 } else {
639 info = LauncherModel.getPhotoFrameInfo(this, cellInfo.screen,
640 cellInfo.cellX, cellInfo.cellY);
641 }
642
643 info.photo = photo;
644 LauncherModel.updateItemInDatabase(this, info);
645 }
646 }
647
648 /**
649 * Starts a new Intent to let the user update the PhotoFrame defined by the
650 * specified Widget.
651 *
652 * @param widget The Widget info defining which PhotoFrame to update.
653 */
654 void updatePhotoFrame(Widget widget) {
655 CellLayout.CellInfo info = new CellLayout.CellInfo();
656 info.screen = widget.screen;
657 info.cellX = widget.cellX;
658 info.cellY = widget.cellY;
659 info.spanX = widget.spanX;
660 info.spanY = widget.spanY;
661 mAddItemCellInfo = info;
662
663 startActivityForResult(createPhotoPickIntent(), Launcher.REQUEST_UPDATE_PHOTO);
664 }
665
666 /**
667 * Creates an Intent used to let the user pick a photo for a PhotoFrame.
668 *
669 * @return The Intent to pick a photo suited for a PhotoFrame.
670 */
671 private static Intent createPhotoPickIntent() {
672 // TODO: Move this method to PhotoFrame?
673 // TODO: get these values from constants somewhere
674 // TODO: Adjust the PhotoFrame's image size to avoid on the fly scaling
675 Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
676 intent.setType("image/*");
677 intent.putExtra("crop", "true");
678 intent.putExtra("aspectX", 1);
679 intent.putExtra("aspectY", 1);
680 intent.putExtra("outputX", 192);
681 intent.putExtra("outputY", 192);
682 intent.putExtra("noFaceDetection", true);
683 intent.putExtra("return-data", true);
684 return intent;
685 }
686
687 @Override
688 protected void onNewIntent(Intent intent) {
689 super.onNewIntent(intent);
690
691 // Close the menu
692 if (Intent.ACTION_MAIN.equals(intent.getAction())) {
693 getWindow().closeAllPanels();
694
695 try {
696 dismissDialog(DIALOG_CREATE_SHORTCUT);
697 // Unlock the workspace if the dialog was showing
698 mWorkspace.unlock();
699 } catch (Exception e) {
700 // An exception is thrown if the dialog is not visible, which is fine
701 }
702
703 try {
704 dismissDialog(DIALOG_RENAME_FOLDER);
705 // Unlock the workspace if the dialog was showing
706 mWorkspace.unlock();
707 } catch (Exception e) {
708 // An exception is thrown if the dialog is not visible, which is fine
709 }
710
711 // If we are already in front we go back to the default screen,
712 // otherwise we don't
713 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) !=
714 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) {
715 if (!mWorkspace.isDefaultScreenShowing()) {
716 mWorkspace.moveToDefaultScreen();
717 }
718 closeDrawer();
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800719 View v = getWindow().peekDecorView();
720 if (v != null && v.getWindowToken() != null) {
721 InputMethodManager imm = (InputMethodManager)getSystemService(
722 INPUT_METHOD_SERVICE);
723 imm.hideSoftInputFromWindow(v.getWindowToken());
724 }
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700725 } else {
726 closeDrawer(false);
727 }
728 }
729 }
730
731 @Override
732 protected void onSaveInstanceState(Bundle outState) {
733 outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen());
734
735 final ArrayList<Folder> folders = mWorkspace.getOpenFolders();
736 if (folders.size() > 0) {
737 final int count = folders.size();
738 long[] ids = new long[count];
739 for (int i = 0; i < count; i++) {
740 final FolderInfo info = folders.get(i).getInfo();
741 ids[i] = info.id;
742 }
743 outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
744 } else {
745 super.onSaveInstanceState(outState);
746 }
747
748 if (mDrawer.isOpened()) {
749 outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true);
750 }
751
752 if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) {
753 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
754 final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen);
755
756 outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen);
757 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX);
758 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY);
759 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX);
760 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY);
761 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX());
762 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY());
763 outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS,
764 layout.getOccupiedCells());
765 }
766
767 if (mFolderInfo != null && mWaitingForResult) {
768 outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
769 outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
770 }
771 }
772
773 @Override
774 public void onDestroy() {
775 mDestroyed = true;
776
777 super.onDestroy();
778
779 TextKeyListener.getInstance().release();
780
781 mAllAppsGrid.clearTextFilter();
782 mAllAppsGrid.setAdapter(null);
783 sModel.unbind();
784 sModel.abortLoaders();
785
786 getContentResolver().unregisterContentObserver(mObserver);
787 unregisterReceiver(mApplicationsReceiver);
788 }
789
790 @Override
791 public void startActivityForResult(Intent intent, int requestCode) {
792 mWaitingForResult = true;
793 super.startActivityForResult(intent, requestCode);
794 }
795
796 @Override
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800797 public void startSearch(String initialQuery, boolean selectInitialQuery,
798 Bundle appSearchData, boolean globalSearch) {
799 if (appSearchData == null) {
800 appSearchData = new Bundle();
801 appSearchData.putString(SearchManager.SOURCE, "launcher-search");
802 }
803 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
804 }
805
806 @Override
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700807 public boolean onCreateOptionsMenu(Menu menu) {
808 if (mDesktopLocked) return false;
809
810 super.onCreateOptionsMenu(menu);
811 menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
812 .setIcon(android.R.drawable.ic_menu_add)
813 .setAlphabeticShortcut('A');
814 menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
815 .setIcon(R.drawable.ic_menu_gallery)
816 .setAlphabeticShortcut('W');
817 menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
818 .setIcon(android.R.drawable.ic_search_category_default)
819 .setAlphabeticShortcut(SearchManager.MENU_KEY);
820 menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
821 .setIcon(R.drawable.ic_menu_notifications)
822 .setAlphabeticShortcut('N');
823
824 final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
825 settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
826 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
827
828 menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
829 .setIcon(R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
830 .setIntent(settings);
831
832 return true;
833 }
834
835 @Override
836 public boolean onPrepareOptionsMenu(Menu menu) {
837 super.onPrepareOptionsMenu(menu);
838
839 mMenuAddInfo = mWorkspace.findAllVacantCells(null);
840 menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid);
841
842 return true;
843 }
844
845 @Override
846 public boolean onOptionsItemSelected(MenuItem item) {
847 switch (item.getItemId()) {
848 case MENU_ADD:
849 addItems();
850 return true;
851 case MENU_WALLPAPER_SETTINGS:
852 startWallpaper();
853 return true;
854 case MENU_SEARCH:
855 if (!mWorkspace.snapToSearch()) {
856 onSearchRequested();
857 }
858 return true;
859 case MENU_NOTIFICATIONS:
860 showNotifications();
861 return true;
862 }
863
864 return super.onOptionsItemSelected(item);
865 }
866
867 private void addItems() {
868 showAddDialog(mMenuAddInfo);
869 }
870
871 private void removeShortcutsForPackage(String packageName) {
872 if (packageName != null && packageName.length() > 0) {
873 android.util.Log.d(LOG_TAG, packageName);
874 mWorkspace.removeShortcutsForPackage(packageName);
875 }
876 }
877
878 void addShortcut(Intent intent) {
879 startActivityForResult(intent, REQUEST_CREATE_SHORTCUT);
880 }
881
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800882 void addLiveFolder(Intent intent) {
883 startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);
884 }
885
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700886 void addFolder() {
887 UserFolderInfo folderInfo = new UserFolderInfo();
888 folderInfo.title = getText(R.string.folder_name);
889 int cellX = mAddItemCellInfo.cellX;
890 int cellY = mAddItemCellInfo.cellY;
891
892 // Update the model
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800893 LauncherModel.addItemToDatabase(this, folderInfo, LauncherSettings.Favorites.CONTAINER_DESKTOP,
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700894 mWorkspace.getCurrentScreen(), cellX, cellY, false);
895 sModel.addDesktopItem(folderInfo);
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800896 sModel.addFolder(folderInfo);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700897
898 // Create the view
899 FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
900 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo);
901 mWorkspace.addInCurrentScreen(newFolder, cellX, cellY, 1, 1);
902 }
903
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800904 private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo,
905 boolean insertAtFirst) {
906
907 cellInfo.screen = mWorkspace.getCurrentScreen();
908 final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);
909
910 if (!mRestoring) {
911 sModel.addDesktopItem(info);
912
913 final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this,
914 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
915 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
916 } else if (sModel.isDesktopLoaded()) {
917 sModel.addDesktopItem(info);
918 }
919 }
920
921 static LiveFolderInfo addLiveFolder(Context context, Intent data,
922 CellLayout.CellInfo cellInfo, boolean notify) {
923
924 Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
925 String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);
926
927 Drawable icon = null;
928 boolean filtered = false;
929 Intent.ShortcutIconResource iconResource = null;
930
931 Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);
932 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
933 try {
934 iconResource = (Intent.ShortcutIconResource) extra;
935 final PackageManager packageManager = context.getPackageManager();
936 Resources resources = packageManager.getResourcesForApplication(
937 iconResource.packageName);
938 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
939 icon = resources.getDrawable(id);
940 } catch (Exception e) {
941 Log.w(LOG_TAG, "Could not load live folder icon: " + extra);
942 }
943 }
944
945 if (icon == null) {
946 icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder);
947 }
948
949 final LiveFolderInfo info = new LiveFolderInfo();
950 info.icon = icon;
951 info.filtered = filtered;
952 info.title = name;
953 info.iconResource = iconResource;
954 info.uri = data.getData();
955 info.baseIntent = baseIntent;
956 info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
957 LiveFolders.DISPLAY_MODE_GRID);
958
959 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
960 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
961 sModel.addFolder(info);
962
963 return info;
964 }
965
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700966 void getPhotoForPhotoFrame() {
967 startActivityForResult(createPhotoPickIntent(), REQUEST_CHOOSE_PHOTO);
968 }
969
970 void addClock() {
971 final Widget info = Widget.makeClock();
972 addWidget(info);
973 }
974
975 void addSearch() {
976 final Widget info = Widget.makeSearch();
977 addWidget(info);
978 }
979
980 private void addWidget(final Widget info) {
981 final CellLayout.CellInfo cellInfo = mAddItemCellInfo;
982
983 final int[] xy = mCellCoordinates;
984 final int spanX = info.spanX;
985 final int spanY = info.spanY;
986
987 if (!findSlot(cellInfo, xy, spanX, spanY)) return;
988
989 sModel.addDesktopItem(info);
The Android Open Source Projectd097a182008-12-17 18:05:58 -0800990 LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -0700991 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
992
993 final View view = mInflater.inflate(info.layoutResource, null);
994 view.setTag(info);
995
996 mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY);
997 }
998
999 private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) {
1000 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1001 boolean[] occupied = mSavedState != null ?
1002 mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null;
1003 cellInfo = mWorkspace.findAllVacantCells(occupied);
1004 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1005 Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1006 return false;
1007 }
1008 }
1009 return true;
1010 }
1011
1012 private void showNotifications() {
1013 final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1014 if (statusBar != null) {
1015 statusBar.expand();
1016 }
1017 }
1018
1019 private void startWallpaper() {
1020 final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1021 startActivity(Intent.createChooser(pickWallpaper, getString(R.string.chooser_wallpaper)));
1022 }
1023
1024 /**
1025 * Registers various intent receivers. The current implementation registers
1026 * only a wallpaper intent receiver to let other applications change the
1027 * wallpaper.
1028 */
1029 private void registerIntentReceivers() {
1030 if (sWallpaperReceiver == null) {
1031 final Application application = getApplication();
1032
1033 sWallpaperReceiver = new WallpaperIntentReceiver(application, this);
1034
1035 IntentFilter filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
1036 application.registerReceiver(sWallpaperReceiver, filter);
1037 } else {
1038 sWallpaperReceiver.setLauncher(this);
1039 }
1040
1041 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
1042 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1043 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1044 filter.addDataScheme("package");
1045 registerReceiver(mApplicationsReceiver, filter);
1046 }
1047
1048 /**
1049 * Registers various content observers. The current implementation registers
1050 * only a favorites observer to keep track of the favorites applications.
1051 */
1052 private void registerContentObservers() {
1053 ContentResolver resolver = getContentResolver();
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001054 resolver.registerContentObserver(LauncherSettings.Favorites.CONTENT_URI, true, mObserver);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001055 }
1056
1057 @Override
1058 public boolean dispatchKeyEvent(KeyEvent event) {
1059 if (event.getAction() == KeyEvent.ACTION_DOWN) {
1060 switch (event.getKeyCode()) {
1061 case KeyEvent.KEYCODE_BACK:
1062 mWorkspace.dispatchKeyEvent(event);
1063 closeFolder();
1064 closeDrawer();
1065 return true;
1066 case KeyEvent.KEYCODE_HOME:
1067 return true;
1068 }
1069 }
1070
1071 return super.dispatchKeyEvent(event);
1072 }
1073
1074 private void closeDrawer() {
1075 closeDrawer(true);
1076 }
1077
1078 private void closeDrawer(boolean animated) {
1079 if (mDrawer.isOpened()) {
1080 if (animated) {
1081 mDrawer.animateClose();
1082 } else {
1083 mDrawer.close();
1084 }
1085 if (mDrawer.hasFocus()) {
1086 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1087 }
1088 }
1089 }
1090
1091 private void closeFolder() {
1092 Folder folder = mWorkspace.getOpenFolder();
1093 if (folder != null) {
1094 closeFolder(folder);
1095 }
1096 }
1097
1098 void closeFolder(Folder folder) {
1099 folder.getInfo().opened = false;
1100 ViewGroup parent = (ViewGroup) folder.getParent();
1101 if (parent != null) {
1102 parent.removeView(folder);
1103 }
1104 folder.onClose();
1105 }
1106
1107 /**
1108 * When the notification that favorites have changed is received, requests
1109 * a favorites list refresh.
1110 */
1111 private void onFavoritesChanged() {
1112 mDesktopLocked = true;
1113 mDrawer.lock();
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001114 sModel.loadUserItems(false, this, false);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001115 }
1116
1117 void onDesktopItemsLoaded() {
1118 if (mDestroyed) return;
1119
1120 bindDesktopItems();
1121 mAllAppsGrid.setAdapter(Launcher.getModel().getApplicationsAdapter());
1122
1123 if (mSavedState != null) {
1124 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1125
1126 final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);
1127 if (userFolders != null) {
1128 for (long folderId : userFolders) {
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001129 final FolderInfo info = sModel.findFolderById(folderId);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001130 if (info != null) {
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001131 openFolder(info);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001132 }
1133 }
1134 final Folder openFolder = mWorkspace.getOpenFolder();
1135 if (openFolder != null) {
1136 openFolder.requestFocus();
1137 } else {
1138 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1139 }
1140 }
1141
1142 final boolean allApps = mSavedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false);
1143 if (allApps) {
1144 mDrawer.open();
1145 mDrawer.requestFocus();
1146 }
1147
1148 mSavedState = null;
1149 }
1150
1151 mDesktopLocked = false;
1152 mDrawer.unlock();
1153 }
1154
1155 /**
1156 * Refreshes the shortcuts shown on the workspace.
1157 */
1158 private void bindDesktopItems() {
1159 final ArrayList<ItemInfo> shortcuts = sModel.getDesktopItems();
1160 if (shortcuts == null) {
1161 return;
1162 }
1163
1164 final Workspace workspace = mWorkspace;
1165 int count = workspace.getChildCount();
1166 for (int i = 0; i < count; i++) {
1167 ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
1168 }
1169
1170 count = shortcuts.size();
1171 for (int i = 0; i < count; i++) {
1172 final ItemInfo item = shortcuts.get(i);
1173 switch (item.itemType) {
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001174 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1175 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001176 final View shortcut = createShortcut((ApplicationInfo) item);
1177 workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
1178 !mDesktopLocked);
1179 break;
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001180 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001181 final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1182 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()),
1183 ((UserFolderInfo) item));
1184 workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
1185 !mDesktopLocked);
1186 break;
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001187 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
1188 final FolderIcon newLiveFolder = LiveFolderIcon.fromXml(
1189 R.layout.live_folder_icon, this,
1190 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()),
1191 ((LiveFolderInfo) item));
1192 workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1,
1193 !mDesktopLocked);
1194 break;
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001195 default:
1196 final Widget widget = (Widget)item;
1197 final View view = createWidget(mInflater, widget);
1198 view.setTag(widget);
1199 workspace.addWidget(view, widget, !mDesktopLocked);
1200 }
1201 }
1202
1203 workspace.requestLayout();
1204 }
1205
1206 private View createWidget(LayoutInflater inflater, Widget widget) {
1207 final Workspace workspace = mWorkspace;
1208 final int screen = workspace.getCurrentScreen();
1209 View v = inflater.inflate(widget.layoutResource,
1210 (ViewGroup) workspace.getChildAt(screen), false);
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001211 if (widget.itemType == LauncherSettings.Favorites.ITEM_TYPE_WIDGET_PHOTO_FRAME) {
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001212 ((ImageView)v).setImageBitmap(widget.photo);
1213 }
1214 return v;
1215 }
1216
1217 DragController getDragController() {
1218 return mDragLayer;
1219 }
1220
1221 /**
1222 * Launches the intent referred by the clicked shortcut.
1223 *
1224 * @param v The view representing the clicked shortcut.
1225 */
1226 public void onClick(View v) {
1227 Object tag = v.getTag();
1228 if (tag instanceof ApplicationInfo) {
1229 // Open shortcut
1230 final Intent intent = ((ApplicationInfo) tag).intent;
1231 startActivitySafely(intent);
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001232 } else if (tag instanceof FolderInfo) {
1233 handleFolderClick((FolderInfo) tag);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001234 }
1235 }
1236
1237 void startActivitySafely(Intent intent) {
1238 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1239 try {
1240 startActivity(intent);
1241 } catch (ActivityNotFoundException e) {
1242 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1243 }
1244 }
1245
1246 private void handleFolderClick(FolderInfo folderInfo) {
1247 if (!folderInfo.opened) {
1248 // Close any open folder
1249 closeFolder();
1250 // Open the requested folder
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001251 openFolder(folderInfo);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001252 } else {
1253 // Find the open folder...
1254 Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
1255 int folderScreen;
1256 if (openFolder != null) {
1257 folderScreen = mWorkspace.getScreenForView(openFolder);
1258 // .. and close it
1259 closeFolder(openFolder);
1260 if (folderScreen != mWorkspace.getCurrentScreen()) {
1261 // Close any folder open on the current screen
1262 closeFolder();
1263 // Pull the folder onto this screen
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001264 openFolder(folderInfo);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001265 }
1266 }
1267 }
1268 }
1269
1270 private void loadWallpaper() {
1271 // The first time the application is started, we load the wallpaper from
1272 // the ApplicationContext
1273 if (sWallpaper == null) {
1274 final Drawable drawable = getWallpaper();
1275 if (drawable instanceof BitmapDrawable) {
1276 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1277 } else {
1278 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1279 }
1280 }
1281 mWorkspace.loadWallpaper(sWallpaper);
1282 }
1283
1284 /**
1285 * Opens the user fodler described by the specified tag. The opening of the folder
1286 * is animated relative to the specified View. If the View is null, no animation
1287 * is played.
1288 *
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001289 * @param folderInfo The FolderInfo describing the folder to open.
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001290 */
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001291 private void openFolder(FolderInfo folderInfo) {
1292 Folder openFolder;
1293
1294 if (folderInfo instanceof UserFolderInfo) {
1295 openFolder = UserFolder.fromXml(this);
1296 } else if (folderInfo instanceof LiveFolderInfo) {
1297 openFolder = com.android.launcher.LiveFolder.fromXml(this, folderInfo);
1298 } else {
1299 return;
1300 }
1301
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001302 openFolder.setDragger(mDragLayer);
1303 openFolder.setLauncher(this);
1304
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001305 openFolder.bind(folderInfo);
1306 folderInfo.opened = true;
1307
1308 mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4);
1309 openFolder.onOpen();
1310 }
1311
1312 /**
1313 * Returns true if the workspace is being loaded. When the workspace is loading,
1314 * no user interaction should be allowed to avoid any conflict.
1315 *
1316 * @return True if the workspace is locked, false otherwise.
1317 */
1318 boolean isWorkspaceLocked() {
1319 return mDesktopLocked;
1320 }
1321
1322 public boolean onLongClick(View v) {
1323 if (mDesktopLocked) {
1324 return false;
1325 }
1326
1327 if (!(v instanceof CellLayout)) {
1328 v = (View) v.getParent();
1329 }
1330
1331 CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();
1332
1333 // This happens when long clicking an item with the dpad/trackball
1334 if (cellInfo == null) {
1335 return false;
1336 }
1337
1338 if (mWorkspace.allowLongPress()) {
1339 if (cellInfo.cell == null) {
1340 if (cellInfo.valid) {
1341 // User long pressed on empty space
1342 showAddDialog(cellInfo);
1343 }
1344 } else {
1345 if (!(cellInfo.cell instanceof Folder)) {
1346 // User long pressed on an item
1347 mWorkspace.startDrag(cellInfo);
1348 }
1349 }
1350 }
1351 return true;
1352 }
1353
1354 static LauncherModel getModel() {
1355 return sModel;
1356 }
1357
1358 void closeAllApplications() {
1359 mDrawer.close();
1360 }
1361
1362 boolean isDrawerDown() {
1363 return !mDrawer.isMoving() && !mDrawer.isOpened();
1364 }
1365
1366 Workspace getWorkspace() {
1367 return mWorkspace;
1368 }
1369
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001370 GridView getApplicationsGrid() {
1371 return mAllAppsGrid;
1372 }
1373
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001374 @Override
1375 protected Dialog onCreateDialog(int id) {
1376 switch (id) {
1377 case DIALOG_CREATE_SHORTCUT:
1378 return new CreateShortcut().createDialog();
1379 case DIALOG_RENAME_FOLDER:
1380 return new RenameFolder().createDialog();
1381 }
1382
1383 return super.onCreateDialog(id);
1384 }
1385
1386 @Override
1387 protected void onPrepareDialog(int id, Dialog dialog) {
1388 switch (id) {
1389 case DIALOG_CREATE_SHORTCUT:
1390 mWorkspace.lock();
1391 break;
1392 case DIALOG_RENAME_FOLDER:
1393 mWorkspace.lock();
1394 EditText input = (EditText) dialog.findViewById(R.id.folder_name);
1395 final CharSequence text = mFolderInfo.title;
1396 input.setText(text);
1397 input.setSelection(0, text.length());
1398 break;
1399 }
1400 }
1401
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001402 void showRenameDialog(FolderInfo info) {
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001403 mFolderInfo = info;
1404 mWaitingForResult = true;
1405 showDialog(DIALOG_RENAME_FOLDER);
1406 }
1407
1408 private void showAddDialog(CellLayout.CellInfo cellInfo) {
1409 mAddItemCellInfo = cellInfo;
1410 mWaitingForResult = true;
1411 showDialog(DIALOG_CREATE_SHORTCUT);
1412 }
1413
1414 private class RenameFolder {
1415 private EditText mInput;
1416
1417 Dialog createDialog() {
1418 mWaitingForResult = true;
1419 final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
1420 mInput = (EditText) layout.findViewById(R.id.folder_name);
1421
1422 AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1423 builder.setIcon(0);
1424 builder.setTitle(getString(R.string.rename_folder_title));
1425 builder.setCancelable(true);
1426 builder.setOnCancelListener(new Dialog.OnCancelListener() {
1427 public void onCancel(DialogInterface dialog) {
1428 cleanup();
1429 }
1430 });
1431 builder.setNegativeButton(getString(R.string.cancel_action),
1432 new Dialog.OnClickListener() {
1433 public void onClick(DialogInterface dialog, int which) {
1434 cleanup();
1435 }
1436 }
1437 );
1438 builder.setPositiveButton(getString(R.string.rename_action),
1439 new Dialog.OnClickListener() {
1440 public void onClick(DialogInterface dialog, int which) {
1441 changeFolderName();
1442 }
1443 }
1444 );
1445 builder.setView(layout);
1446 return builder.create();
1447 }
1448
1449 private void changeFolderName() {
1450 final String name = mInput.getText().toString();
1451 if (!TextUtils.isEmpty(name)) {
1452 // Make sure we have the right folder info
1453 mFolderInfo = sModel.findFolderById(mFolderInfo.id);
1454 mFolderInfo.title = name;
1455 LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
1456
1457 if (mDesktopLocked) {
1458 mDrawer.lock();
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001459 sModel.loadUserItems(false, Launcher.this, false);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001460 } else {
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001461 final FolderIcon folderIcon = (FolderIcon)
1462 mWorkspace.getViewForTag(mFolderInfo);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001463 if (folderIcon != null) {
1464 folderIcon.setText(name);
1465 getWorkspace().requestLayout();
1466 } else {
1467 mDesktopLocked = true;
1468 mDrawer.lock();
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001469 sModel.loadUserItems(false, Launcher.this, false);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001470 }
1471 }
1472 }
1473 cleanup();
1474 }
1475
1476 private void cleanup() {
1477 mWorkspace.unlock();
1478 dismissDialog(DIALOG_RENAME_FOLDER);
1479 mWaitingForResult = false;
1480 mFolderInfo = null;
1481 }
1482 }
1483
1484 /**
1485 * Displays the shortcut creation dialog and launches, if necessary, the
1486 * appropriate activity.
1487 */
1488 private class CreateShortcut implements ExpandableListView.OnChildClickListener,
1489 DialogInterface.OnCancelListener, ExpandableListView.OnGroupExpandListener {
1490 private AddAdapter mAdapter;
1491 private ExpandableListView mList;
1492
1493 Dialog createDialog() {
1494 mWaitingForResult = true;
1495 mAdapter = new AddAdapter(Launcher.this, false);
1496
1497 final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1498 builder.setTitle(getString(R.string.menu_item_add_item));
1499 builder.setIcon(0);
1500
1501 mList = (ExpandableListView)
1502 View.inflate(Launcher.this, R.layout.create_shortcut_list, null);
1503 mList.setAdapter(mAdapter);
1504 mList.setOnChildClickListener(this);
1505 mList.setOnGroupExpandListener(this);
1506 builder.setView(mList);
1507 builder.setInverseBackgroundForced(true);
1508
1509 AlertDialog dialog = builder.create();
1510 dialog.setOnCancelListener(this);
1511
1512 WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
1513 attributes.gravity = Gravity.TOP;
1514 dialog.onWindowAttributesChanged(attributes);
1515
1516 return dialog;
1517 }
1518
1519 public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
1520 int childPosition, long id) {
1521 mAdapter.performAction(groupPosition, childPosition);
1522 cleanup();
1523 return true;
1524 }
1525
1526 public void onCancel(DialogInterface dialog) {
1527 mWaitingForResult = false;
1528 cleanup();
1529 }
1530
1531 private void cleanup() {
1532 mWorkspace.unlock();
1533 dismissDialog(DIALOG_CREATE_SHORTCUT);
1534 }
1535
1536 public void onGroupExpand(int groupPosition) {
1537 long packged = ExpandableListView.getPackedPositionForGroup(groupPosition);
1538 int position = mList.getFlatListPosition(packged);
1539 mList.setSelectionFromTop(position, 0);
1540 }
1541 }
1542
1543 /**
1544 * Receives notifications when applications are added/removed.
1545 */
1546 private class ApplicationsIntentReceiver extends BroadcastReceiver {
1547 @Override
1548 public void onReceive(Context context, Intent intent) {
1549 //noinspection ConstantConditions
1550 if (REMOVE_SHORTCUT_ON_PACKAGE_REMOVE &&
1551 Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
1552 removeShortcutsForPackage(intent.getData().getSchemeSpecificPart());
1553 }
1554 removeDialog(DIALOG_CREATE_SHORTCUT);
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001555 sModel.loadApplications(false, Launcher.this, false);
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001556 }
1557 }
1558
1559 /**
1560 * Receives notifications whenever the user favorites have changed.
1561 */
1562 private class FavoritesChangeObserver extends ContentObserver {
1563 public FavoritesChangeObserver() {
The Android Open Source Projectd097a182008-12-17 18:05:58 -08001564 super(new Handler());
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001565 }
1566
1567 @Override
1568 public void onChange(boolean selfChange) {
1569 onFavoritesChanged();
1570 }
1571 }
1572
The Android Open Source Projectc8f00b62008-10-21 07:00:00 -07001573 /**
1574 * Receives intents from other applications to change the wallpaper.
1575 */
1576 private static class WallpaperIntentReceiver extends BroadcastReceiver {
1577 private final Application mApplication;
1578 private WeakReference<Launcher> mLauncher;
1579
1580 WallpaperIntentReceiver(Application application, Launcher launcher) {
1581 mApplication = application;
1582 setLauncher(launcher);
1583 }
1584
1585 void setLauncher(Launcher launcher) {
1586 mLauncher = new WeakReference<Launcher>(launcher);
1587 }
1588
1589 @Override
1590 public void onReceive(Context context, Intent intent) {
1591 // Load the wallpaper from the ApplicationContext and store it locally
1592 // until the Launcher Activity is ready to use it
1593 final Drawable drawable = mApplication.getWallpaper();
1594 if (drawable instanceof BitmapDrawable) {
1595 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1596 } else {
1597 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1598 }
1599
1600 // If Launcher is alive, notify we have a new wallpaper
1601 if (mLauncher != null) {
1602 final Launcher launcher = mLauncher.get();
1603 if (launcher != null) {
1604 launcher.loadWallpaper();
1605 }
1606 }
1607 }
1608 }
1609
1610 private class DrawerManager implements SlidingDrawer.OnDrawerOpenListener,
1611 SlidingDrawer.OnDrawerCloseListener, SlidingDrawer.OnDrawerScrollListener {
1612 private boolean mOpen;
1613
1614 public void onDrawerOpened() {
1615 if (!mOpen) {
1616 mHandleIcon.reverseTransition(150);
1617 mOpen = true;
1618 }
1619 }
1620
1621 public void onDrawerClosed() {
1622 if (mOpen) {
1623 mHandleIcon.reverseTransition(150);
1624 mOpen = false;
1625 }
1626 mAllAppsGrid.setSelection(0);
1627 mAllAppsGrid.clearTextFilter();
1628 mWorkspace.clearChildrenCache();
1629 }
1630
1631 public void onScrollStarted() {
1632 mWorkspace.enableChildrenCache();
1633 }
1634
1635 public void onScrollEnded() {
1636 }
1637 }
1638}