blob: 36b2090e1838db9535188ff11d258923ea823075 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
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
Joe Onoratoa5902522009-07-30 13:37:37 -070017package com.android.launcher2;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
19import android.content.ComponentName;
20import android.content.ContentResolver;
21import android.content.ContentValues;
22import android.content.Intent;
23import android.content.Context;
24import android.content.pm.ActivityInfo;
25import android.content.pm.PackageManager;
26import android.content.pm.ResolveInfo;
27import android.content.res.Resources;
28import android.database.Cursor;
29import android.graphics.Bitmap;
30import android.graphics.BitmapFactory;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070031import android.graphics.drawable.Drawable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080032import android.net.Uri;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070033import static android.util.Log.*;
Joe Onorato9c1289c2009-08-17 11:03:03 -040034import android.util.Log;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.os.Process;
Joe Onorato9c1289c2009-08-17 11:03:03 -040036import android.os.SystemClock;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080037
Joe Onorato9c1289c2009-08-17 11:03:03 -040038import java.lang.ref.WeakReference;
39import java.net.URISyntaxException;
40import java.text.Collator;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import java.util.ArrayList;
Joe Onorato9c1289c2009-08-17 11:03:03 -040042import java.util.Comparator;
43import java.util.Collections;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080044import java.util.HashMap;
45import java.util.List;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080046
47/**
48 * Maintains in-memory state of the Launcher. It is expected that there should be only one
49 * LauncherModel object held in a static. Also provide APIs for updating the database state
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070050 * for the Launcher.
The Android Open Source Project31dd5032009-03-03 19:32:27 -080051 */
52public class LauncherModel {
Romain Guy829f56a2009-03-27 16:58:13 -070053 static final boolean DEBUG_LOADERS = true;
Joe Onorato9c1289c2009-08-17 11:03:03 -040054 static final String TAG = "Launcher.Model";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070055
Joe Onorato9c1289c2009-08-17 11:03:03 -040056 private final Object mLock = new Object();
57 private DeferredHandler mHandler = new DeferredHandler();
58 private Loader mLoader = new Loader();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080059
Joe Onorato9c1289c2009-08-17 11:03:03 -040060 private WeakReference<Callbacks> mCallbacks;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080061
Joe Onorato9c1289c2009-08-17 11:03:03 -040062 private AllAppsList mAllAppsList = new AllAppsList();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080063
Joe Onorato9c1289c2009-08-17 11:03:03 -040064 public interface Callbacks {
65 public int getCurrentWorkspaceScreen();
66 public void startBinding();
67 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
68 public void finishBindingItems();
69 public void bindAppWidget(LauncherAppWidgetInfo info);
70 public void bindAllApplications(ArrayList<ApplicationInfo> apps);
71 public void bindPackageAdded(ArrayList<ApplicationInfo> apps);
72 public void bindPackageUpdated(String packageName, ArrayList<ApplicationInfo> apps);
73 public void bindPackageRemoved(String packageName, ArrayList<ApplicationInfo> apps);
74 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -080075
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076
Joe Onorato9c1289c2009-08-17 11:03:03 -040077 /**
78 * Adds an item to the DB if it was not created previously, or move it to a new
79 * <container, screen, cellX, cellY>
80 */
81 static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
82 int screen, int cellX, int cellY) {
83 if (item.container == ItemInfo.NO_ID) {
84 // From all apps
85 addItemToDatabase(context, item, container, screen, cellX, cellY, false);
86 } else {
87 // From somewhere else
88 moveItemInDatabase(context, item, container, screen, cellX, cellY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -080089 }
90 }
91
92 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -040093 * Move an item in the DB to a new <container, screen, cellX, cellY>
The Android Open Source Projectbc219c32009-03-09 11:52:14 -070094 */
Joe Onorato9c1289c2009-08-17 11:03:03 -040095 static void moveItemInDatabase(Context context, ItemInfo item, long container, int screen,
96 int cellX, int cellY) {
97 item.container = container;
98 item.screen = screen;
99 item.cellX = cellX;
100 item.cellY = cellY;
101
102 final ContentValues values = new ContentValues();
103 final ContentResolver cr = context.getContentResolver();
104
105 values.put(LauncherSettings.Favorites.CONTAINER, item.container);
106 values.put(LauncherSettings.Favorites.CELLX, item.cellX);
107 values.put(LauncherSettings.Favorites.CELLY, item.cellY);
108 values.put(LauncherSettings.Favorites.SCREEN, item.screen);
109
110 cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700111 }
112
113 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400114 * Returns true if the shortcuts already exists in the database.
115 * we identify a shortcut by its title and intent.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800116 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400117 static boolean shortcutExists(Context context, String title, Intent intent) {
118 final ContentResolver cr = context.getContentResolver();
119 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
120 new String[] { "title", "intent" }, "title=? and intent=?",
121 new String[] { title, intent.toUri(0) }, null);
122 boolean result = false;
123 try {
124 result = c.moveToFirst();
125 } finally {
126 c.close();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800127 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400128 return result;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700129 }
130
Joe Onorato9c1289c2009-08-17 11:03:03 -0400131 /**
132 * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
133 */
134 FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
135 final ContentResolver cr = context.getContentResolver();
136 Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
137 "_id=? and (itemType=? or itemType=?)",
138 new String[] { String.valueOf(id),
139 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
140 String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700141
Joe Onorato9c1289c2009-08-17 11:03:03 -0400142 try {
143 if (c.moveToFirst()) {
144 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
145 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
146 final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
147 final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
148 final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
149 final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800150
Joe Onorato9c1289c2009-08-17 11:03:03 -0400151 FolderInfo folderInfo = null;
152 switch (c.getInt(itemTypeIndex)) {
153 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
154 folderInfo = findOrMakeUserFolder(folderList, id);
155 break;
156 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
157 folderInfo = findOrMakeLiveFolder(folderList, id);
158 break;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700159 }
160
Joe Onorato9c1289c2009-08-17 11:03:03 -0400161 folderInfo.title = c.getString(titleIndex);
162 folderInfo.id = id;
163 folderInfo.container = c.getInt(containerIndex);
164 folderInfo.screen = c.getInt(screenIndex);
165 folderInfo.cellX = c.getInt(cellXIndex);
166 folderInfo.cellY = c.getInt(cellYIndex);
167
168 return folderInfo;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700169 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400170 } finally {
171 c.close();
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700172 }
173
174 return null;
175 }
176
Joe Onorato9c1289c2009-08-17 11:03:03 -0400177 /**
178 * Add an item to the database in a specified container. Sets the container, screen, cellX and
179 * cellY fields of the item. Also assigns an ID to the item.
180 */
181 static void addItemToDatabase(Context context, ItemInfo item, long container,
182 int screen, int cellX, int cellY, boolean notify) {
183 item.container = container;
184 item.screen = screen;
185 item.cellX = cellX;
186 item.cellY = cellY;
187
188 final ContentValues values = new ContentValues();
189 final ContentResolver cr = context.getContentResolver();
190
191 item.onAddToDatabase(values);
192
193 Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
194 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
195
196 if (result != null) {
197 item.id = Integer.parseInt(result.getPathSegments().get(1));
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700198 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700199 }
200
Joe Onorato9c1289c2009-08-17 11:03:03 -0400201 /**
202 * Update an item to the database in a specified container.
203 */
204 static void updateItemInDatabase(Context context, ItemInfo item) {
205 final ContentValues values = new ContentValues();
206 final ContentResolver cr = context.getContentResolver();
207
208 item.onAddToDatabase(values);
209
210 cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
211 }
212
213 /**
214 * Removes the specified item from the database
215 * @param context
216 * @param item
217 */
218 static void deleteItemFromDatabase(Context context, ItemInfo item) {
219 final ContentResolver cr = context.getContentResolver();
220
221 cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
222 }
223
224 /**
225 * Remove the contents of the specified folder from the database
226 */
227 static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
228 final ContentResolver cr = context.getContentResolver();
229
230 cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
231 cr.delete(LauncherSettings.Favorites.CONTENT_URI,
232 LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
233 }
234
235 /**
236 * Set this as the current Launcher activity object for the loader.
237 */
238 public void initialize(Callbacks callbacks) {
239 synchronized (mLock) {
240 mCallbacks = new WeakReference<Callbacks>(callbacks);
241 }
242 }
243
244 public void startLoader(Context context, boolean isLaunching) {
245 mLoader.startLoader(context, isLaunching);
246 }
247
248 public void stopLoader() {
249 mLoader.stopLoader();
250 }
251
252 public void setWorkspaceDirty() {
253 mLoader.setWorkspaceDirty();
254 }
255
256 /**
257 * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
258 * ACTION_PACKAGE_CHANGED.
259 */
260 public void onReceiveIntent(Context context, Intent intent) {
261 final String packageName = intent.getData().getSchemeSpecificPart();
262
263 ArrayList<ApplicationInfo> added = null;
264 ArrayList<ApplicationInfo> removed = null;
265 ArrayList<ApplicationInfo> modified = null;
266 boolean update = false;
267 boolean remove = false;
268
269 synchronized (mLock) {
270 final String action = intent.getAction();
271 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
272
273 if (packageName == null || packageName.length() == 0) {
274 // they sent us a bad intent
275 return;
276 }
277
278 if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
279 mAllAppsList.updatePackage(context, packageName);
280 update = true;
281 } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
282 if (!replacing) {
283 mAllAppsList.removePackage(packageName);
284 remove = true;
285 }
286 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
287 // later, we will update the package at this time
288 } else {
289 if (!replacing) {
290 mAllAppsList.addPackage(context, packageName);
291 } else {
292 mAllAppsList.updatePackage(context, packageName);
293 update = true;
294 }
295 }
296
297 if (mAllAppsList.added.size() > 0) {
298 added = mAllAppsList.added;
299 added = new ArrayList();
300 }
301 if (mAllAppsList.removed.size() > 0) {
302 removed = mAllAppsList.removed;
303 removed = new ArrayList();
304 for (ApplicationInfo info: removed) {
305 AppInfoCache.remove(info.intent.getComponent());
306 }
307 }
308 if (mAllAppsList.modified.size() > 0) {
309 modified = mAllAppsList.modified;
310 modified = new ArrayList();
311 }
312
313 final Callbacks callbacks = mCallbacks.get();
314 if (callbacks == null) {
315 return;
316 }
317
318 if (added != null) {
319 final ArrayList<ApplicationInfo> addedFinal = added;
320 mHandler.post(new Runnable() {
321 public void run() {
322 callbacks.bindPackageAdded(addedFinal);
323 }
324 });
325 }
326 if (update || modified != null) {
327 final ArrayList<ApplicationInfo> modifiedFinal = modified;
328 mHandler.post(new Runnable() {
329 public void run() {
330 callbacks.bindPackageUpdated(packageName, modifiedFinal);
331 }
332 });
333 }
334 if (remove || removed != null) {
335 final ArrayList<ApplicationInfo> removedFinal = removed;
336 mHandler.post(new Runnable() {
337 public void run() {
338 callbacks.bindPackageRemoved(packageName, removedFinal);
339 }
340 });
341 }
342 }
343 }
344
345 public class Loader {
346 private static final int ITEMS_CHUNK = 6;
347
348 private LoaderThread mLoaderThread;
349
350 private int mLastWorkspaceSeq = 0;
351 private int mWorkspaceSeq = 1;
352
353 private int mLastAllAppsSeq = 0;
354 private int mAllAppsSeq = 1;
355
356 final ArrayList<ItemInfo> mItems = new ArrayList();
357 final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList();
358 final HashMap<Long, FolderInfo> folders = new HashMap();
359
360 /**
361 * Call this from the ui thread so the handler is initialized on the correct thread.
362 */
363 public Loader() {
364 }
365
366 public void startLoader(Context context, boolean isLaunching) {
367 synchronized (mLock) {
368 Log.d(TAG, "startLoader isLaunching=" + isLaunching);
369 // Don't bother to start the thread if we know it's not going to do anything
370 if (mCallbacks.get() != null) {
371 LoaderThread oldThread = mLoaderThread;
372 if (oldThread != null) {
373 if (oldThread.isLaunching()) {
374 // don't downgrade isLaunching if we're already running
375 isLaunching = true;
376 }
377 oldThread.stopLocked();
378 }
379 mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
380 mLoaderThread.start();
381 }
382 }
383 }
384
385 public void stopLoader() {
386 synchronized (mLock) {
387 if (mLoaderThread != null) {
388 mLoaderThread.stopLocked();
389 }
390 }
391 }
392
393 public void setWorkspaceDirty() {
394 synchronized (mLock) {
395 mWorkspaceSeq++;
396 }
397 }
398
399 public void setAllAppsDirty() {
400 synchronized (mLock) {
401 mAllAppsSeq++;
402 }
403 }
404
405 /**
406 * Runnable for the thread that loads the contents of the launcher:
407 * - workspace icons
408 * - widgets
409 * - all apps icons
410 */
411 private class LoaderThread extends Thread {
412 private Context mContext;
413 private Thread mWaitThread;
414 private boolean mIsLaunching;
415 private boolean mStopped;
416 private boolean mWorkspaceDoneBinding;
417
418 LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
419 mContext = context;
420 mWaitThread = waitThread;
421 mIsLaunching = isLaunching;
422 }
423
424 boolean isLaunching() {
425 return mIsLaunching;
426 }
427
428 /**
429 * If another LoaderThread was supplied, we need to wait for that to finish before
430 * we start our processing. This keeps the ordering of the setting and clearing
431 * of the dirty flags correct by making sure we don't start processing stuff until
432 * they've had a chance to re-set them. We do this waiting the worker thread, not
433 * the ui thread to avoid ANRs.
434 */
435 private void waitForOtherThread() {
436 if (mWaitThread != null) {
437 boolean done = false;
438 while (!done) {
439 try {
440 mWaitThread.join();
441 } catch (InterruptedException ex) {
442 }
443 }
444 mWaitThread = null;
445 }
446 }
447
448 public void run() {
449 waitForOtherThread();
450
451 // Elevate priority when Home launches for the first time to avoid
452 // starving at boot time. Staring at a blank home is not cool.
453 synchronized (mLock) {
454 android.os.Process.setThreadPriority(mIsLaunching
455 ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
456 }
457
458 // Load the workspace only if it's dirty.
459 int workspaceSeq;
460 boolean workspaceDirty;
461 synchronized (mLock) {
462 workspaceSeq = mWorkspaceSeq;
463 workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
464 }
465 if (workspaceDirty) {
466 loadWorkspace();
467 }
468 synchronized (mLock) {
469 // If we're not stopped, and nobody has incremented mWorkspaceSeq.
470 if (mStopped) {
471 return;
472 }
473 if (workspaceSeq == mWorkspaceSeq) {
474 mLastWorkspaceSeq = mWorkspaceSeq;
475 }
476 }
477
478 // Bind the workspace
479 bindWorkspace();
480
481 // Wait until the either we're stopped or the other threads are done.
482 // This way we don't start loading all apps until the workspace has settled
483 // down.
484 synchronized (LoaderThread.this) {
485 mHandler.post(new Runnable() {
486 public void run() {
487 synchronized (LoaderThread.this) {
488 mWorkspaceDoneBinding = true;
489 Log.d(TAG, "done with workspace");
490 LoaderThread.this.notify();
491 }
492 }
493 });
494 Log.d(TAG, "waiting to be done with workspace");
495 while (!mStopped && !mWorkspaceDoneBinding) {
496 try {
497 this.wait();
498 } catch (InterruptedException ex) {
499 }
500 }
501 Log.d(TAG, "done waiting to be done with workspace");
502 }
503
504 // Load all apps if they're dirty
505 int allAppsSeq;
506 boolean allAppsDirty;
507 synchronized (mLock) {
508 allAppsSeq = mAllAppsSeq;
509 allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
510 }
511 if (allAppsDirty) {
512 loadAllApps();
513 }
514 synchronized (mLock) {
515 // If we're not stopped, and nobody has incremented mAllAppsSeq.
516 if (mStopped) {
517 return;
518 }
519 if (allAppsSeq == mAllAppsSeq) {
520 mLastAllAppsSeq = mAllAppsSeq;
521 }
522 }
523
524 // Bind all apps
525 bindAllApps();
526
527 // Clear out this reference, otherwise we end up holding it until all of the
528 // callback runnables are done.
529 mContext = null;
530
531 synchronized (mLock) {
532 // Setting the reference is atomic, but we can't do it inside the other critical
533 // sections.
534 mLoaderThread = null;
535 return;
536 }
537 }
538
539 public void stopLocked() {
540 synchronized (LoaderThread.this) {
541 mStopped = true;
542 this.notify();
543 }
544 }
545
546 /**
547 * Gets the callbacks object. If we've been stopped, or if the launcher object
548 * has somehow been garbage collected, return null instead.
549 */
550 Callbacks tryGetCallbacks() {
551 synchronized (mLock) {
552 if (mStopped) {
553 return null;
554 }
555
556 final Callbacks callbacks = mCallbacks.get();
557 if (callbacks == null) {
558 Log.w(TAG, "no mCallbacks");
559 return null;
560 }
561
562 return callbacks;
563 }
564 }
565
566 private void loadWorkspace() {
567 long t = SystemClock.uptimeMillis();
568
569 final Context context = mContext;
570 final ContentResolver contentResolver = context.getContentResolver();
571 final PackageManager manager = context.getPackageManager();
572
573 /* TODO
574 if (mLocaleChanged) {
575 updateShortcutLabels(contentResolver, manager);
576 }
577 */
578
579 final Cursor c = contentResolver.query(
580 LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
581
582 try {
583 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
584 final int intentIndex = c.getColumnIndexOrThrow
585 (LauncherSettings.Favorites.INTENT);
586 final int titleIndex = c.getColumnIndexOrThrow
587 (LauncherSettings.Favorites.TITLE);
588 final int iconTypeIndex = c.getColumnIndexOrThrow(
589 LauncherSettings.Favorites.ICON_TYPE);
590 final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
591 final int iconPackageIndex = c.getColumnIndexOrThrow(
592 LauncherSettings.Favorites.ICON_PACKAGE);
593 final int iconResourceIndex = c.getColumnIndexOrThrow(
594 LauncherSettings.Favorites.ICON_RESOURCE);
595 final int containerIndex = c.getColumnIndexOrThrow(
596 LauncherSettings.Favorites.CONTAINER);
597 final int itemTypeIndex = c.getColumnIndexOrThrow(
598 LauncherSettings.Favorites.ITEM_TYPE);
599 final int appWidgetIdIndex = c.getColumnIndexOrThrow(
600 LauncherSettings.Favorites.APPWIDGET_ID);
601 final int screenIndex = c.getColumnIndexOrThrow(
602 LauncherSettings.Favorites.SCREEN);
603 final int cellXIndex = c.getColumnIndexOrThrow
604 (LauncherSettings.Favorites.CELLX);
605 final int cellYIndex = c.getColumnIndexOrThrow
606 (LauncherSettings.Favorites.CELLY);
607 final int spanXIndex = c.getColumnIndexOrThrow
608 (LauncherSettings.Favorites.SPANX);
609 final int spanYIndex = c.getColumnIndexOrThrow(
610 LauncherSettings.Favorites.SPANY);
611 final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
612 final int displayModeIndex = c.getColumnIndexOrThrow(
613 LauncherSettings.Favorites.DISPLAY_MODE);
614
615 ApplicationInfo info;
616 String intentDescription;
617 Widget widgetInfo;
618 LauncherAppWidgetInfo appWidgetInfo;
619 int container;
620 long id;
621 Intent intent;
622
623 while (!mStopped && c.moveToNext()) {
624 try {
625 int itemType = c.getInt(itemTypeIndex);
626
627 switch (itemType) {
628 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
629 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
630 intentDescription = c.getString(intentIndex);
631 try {
632 intent = Intent.parseUri(intentDescription, 0);
633 } catch (URISyntaxException e) {
634 continue;
635 }
636
637 if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
638 info = getApplicationInfo(manager, intent, context);
639 } else {
640 info = getApplicationInfoShortcut(c, context, iconTypeIndex,
641 iconPackageIndex, iconResourceIndex, iconIndex);
642 }
643
644 if (info == null) {
645 info = new ApplicationInfo();
646 info.icon = manager.getDefaultActivityIcon();
647 }
648
649 if (info != null) {
650 info.title = c.getString(titleIndex);
651 info.intent = intent;
652
653 info.id = c.getLong(idIndex);
654 container = c.getInt(containerIndex);
655 info.container = container;
656 info.screen = c.getInt(screenIndex);
657 info.cellX = c.getInt(cellXIndex);
658 info.cellY = c.getInt(cellYIndex);
659
660 switch (container) {
661 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
662 mItems.add(info);
663 break;
664 default:
665 // Item is in a user folder
666 UserFolderInfo folderInfo =
667 findOrMakeUserFolder(folders, container);
668 folderInfo.add(info);
669 break;
670 }
671 }
672 break;
673 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
674
675 id = c.getLong(idIndex);
676 UserFolderInfo folderInfo = findOrMakeUserFolder(folders, id);
677
678 folderInfo.title = c.getString(titleIndex);
679
680 folderInfo.id = id;
681 container = c.getInt(containerIndex);
682 folderInfo.container = container;
683 folderInfo.screen = c.getInt(screenIndex);
684 folderInfo.cellX = c.getInt(cellXIndex);
685 folderInfo.cellY = c.getInt(cellYIndex);
686
687 switch (container) {
688 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
689 mItems.add(folderInfo);
690 break;
691 }
692 break;
693 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
694
695 id = c.getLong(idIndex);
696 LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(folders, id);
697
698 intentDescription = c.getString(intentIndex);
699 intent = null;
700 if (intentDescription != null) {
701 try {
702 intent = Intent.parseUri(intentDescription, 0);
703 } catch (URISyntaxException e) {
704 // Ignore, a live folder might not have a base intent
705 }
706 }
707
708 liveFolderInfo.title = c.getString(titleIndex);
709 liveFolderInfo.id = id;
710 container = c.getInt(containerIndex);
711 liveFolderInfo.container = container;
712 liveFolderInfo.screen = c.getInt(screenIndex);
713 liveFolderInfo.cellX = c.getInt(cellXIndex);
714 liveFolderInfo.cellY = c.getInt(cellYIndex);
715 liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
716 liveFolderInfo.baseIntent = intent;
717 liveFolderInfo.displayMode = c.getInt(displayModeIndex);
718
719 loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
720 iconResourceIndex, liveFolderInfo);
721
722 switch (container) {
723 case LauncherSettings.Favorites.CONTAINER_DESKTOP:
724 mItems.add(liveFolderInfo);
725 break;
726 }
727 break;
728 case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
729 widgetInfo = Widget.makeSearch();
730
731 container = c.getInt(containerIndex);
732 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
733 Log.e(TAG, "Widget found where container "
734 + "!= CONTAINER_DESKTOP ignoring!");
735 continue;
736 }
737
738 widgetInfo.id = c.getLong(idIndex);
739 widgetInfo.screen = c.getInt(screenIndex);
740 widgetInfo.container = container;
741 widgetInfo.cellX = c.getInt(cellXIndex);
742 widgetInfo.cellY = c.getInt(cellYIndex);
743
744 mItems.add(widgetInfo);
745 break;
746 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
747 // Read all Launcher-specific widget details
748 int appWidgetId = c.getInt(appWidgetIdIndex);
749 appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
750 appWidgetInfo.id = c.getLong(idIndex);
751 appWidgetInfo.screen = c.getInt(screenIndex);
752 appWidgetInfo.cellX = c.getInt(cellXIndex);
753 appWidgetInfo.cellY = c.getInt(cellYIndex);
754 appWidgetInfo.spanX = c.getInt(spanXIndex);
755 appWidgetInfo.spanY = c.getInt(spanYIndex);
756
757 container = c.getInt(containerIndex);
758 if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
759 Log.e(TAG, "Widget found where container "
760 + "!= CONTAINER_DESKTOP -- ignoring!");
761 continue;
762 }
763 appWidgetInfo.container = c.getInt(containerIndex);
764
765 mAppWidgets.add(appWidgetInfo);
766 break;
767 }
768 } catch (Exception e) {
769 Log.w(TAG, "Desktop items loading interrupted:", e);
770 }
771 }
772 } finally {
773 c.close();
774 }
775 Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
776 }
777
778 /**
779 * Read everything out of our database.
780 */
781 private void bindWorkspace() {
782 final long t = SystemClock.uptimeMillis();
783
784 // Don't use these two variables in any of the callback runnables.
785 // Otherwise we hold a reference to them.
786 Callbacks callbacks = mCallbacks.get();
787 if (callbacks == null) {
788 // This launcher has exited and nobody bothered to tell us. Just bail.
789 Log.w(TAG, "LoaderThread running with no launcher");
790 return;
791 }
792
793 int N;
794 // Tell the workspace that we're about to start firing items at it
795 mHandler.post(new Runnable() {
796 public void run() {
797 Callbacks callbacks = tryGetCallbacks();
798 if (callbacks != null) {
799 callbacks.startBinding();
800 }
801 }
802 });
803 // Add the items to the workspace.
804 N = mItems.size();
805 for (int i=0; i<N; i+=ITEMS_CHUNK) {
806 final int start = i;
807 final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
808 mHandler.post(new Runnable() {
809 public void run() {
810 Callbacks callbacks = tryGetCallbacks();
811 if (callbacks != null) {
812 callbacks.bindItems(mItems, start, start+chunkSize);
813 }
814 }
815 });
816 }
817 // Wait until the queue goes empty.
818 mHandler.postIdle(new Runnable() {
819 public void run() {
820 Log.d(TAG, "Going to start binding widgets soon.");
821 }
822 });
823 // Bind the widgets, one at a time.
824 // WARNING: this is calling into the workspace from the background thread,
825 // but since getCurrentScreen() just returns the int, we should be okay. This
826 // is just a hint for the order, and if it's wrong, we'll be okay.
827 // TODO: instead, we should have that push the current screen into here.
828 final int currentScreen = callbacks.getCurrentWorkspaceScreen();
829 N = mAppWidgets.size();
830 // once for the current screen
831 for (int i=0; i<N; i++) {
832 final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
833 if (widget.screen == currentScreen) {
834 mHandler.post(new Runnable() {
835 public void run() {
836 Callbacks callbacks = tryGetCallbacks();
837 if (callbacks != null) {
838 callbacks.bindAppWidget(widget);
839 }
840 }
841 });
842 }
843 }
844 // once for the other screens
845 for (int i=0; i<N; i++) {
846 final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
847 if (widget.screen != currentScreen) {
848 mHandler.post(new Runnable() {
849 public void run() {
850 Callbacks callbacks = tryGetCallbacks();
851 if (callbacks != null) {
852 callbacks.bindAppWidget(widget);
853 }
854 }
855 });
856 }
857 }
858 // TODO: Bind the folders
859 // Tell the workspace that we're done.
860 mHandler.post(new Runnable() {
861 public void run() {
862 Callbacks callbacks = tryGetCallbacks();
863 if (callbacks != null) {
864 callbacks.finishBindingItems();
865 }
866 }
867 });
868 // If we're profiling, this is the last thing in the queue.
869 mHandler.post(new Runnable() {
870 public void run() {
871 Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
872 if (Launcher.PROFILE_ROTATE) {
873 android.os.Debug.stopMethodTracing();
874 }
875 }
876 });
877 }
878
879 private void loadAllApps() {
880 final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
881 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
882
883 final Callbacks callbacks = tryGetCallbacks();
884 if (callbacks == null) {
885 return;
886 }
887
888 final Context context = mContext;
889 final PackageManager packageManager = context.getPackageManager();
890
891 final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
892
893 synchronized (mLock) {
894 mAllAppsList.clear();
895 if (apps != null) {
896 long t = SystemClock.uptimeMillis();
897
898 int N = apps.size();
899 Utilities.BubbleText bubble = new Utilities.BubbleText(context);
900 for (int i=0; i<N && !mStopped; i++) {
901 // This builds the icon bitmaps.
902 mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
903 }
904 Collections.sort(mAllAppsList.data, sComparator);
905 Collections.sort(mAllAppsList.added, sComparator);
906 Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms");
907 }
908 }
909 }
910
911 private void bindAllApps() {
912 synchronized (mLock) {
913 final ArrayList<ApplicationInfo> results = mAllAppsList.added;
914 mAllAppsList.added = new ArrayList();
915 mHandler.post(new Runnable() {
916 public void run() {
917 long t = SystemClock.uptimeMillis();
918
919 Callbacks callbacks = tryGetCallbacks();
920 if (callbacks != null) {
921 callbacks.bindAllApplications(results);
922 }
923
924 Log.d(TAG, "bound app icons in "
925 + (SystemClock.uptimeMillis()-t) + "ms");
926 }
927 });
928 }
929 }
930 }
931 }
932
933 /**
934 * Make an ApplicationInfo object for an application.
935 */
936 private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
937 Context context) {
938 final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
939
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700940 if (resolveInfo == null) {
941 return null;
942 }
943
Joe Onorato9c1289c2009-08-17 11:03:03 -0400944 final ApplicationInfo info = new ApplicationInfo();
945 final ActivityInfo activityInfo = resolveInfo.activityInfo;
946 info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context, false);
947 if (info.title == null || info.title.length() == 0) {
948 info.title = activityInfo.loadLabel(manager);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700949 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400950 if (info.title == null) {
951 info.title = "";
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700952 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400953 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
954 return info;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800955 }
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700956
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800957 /**
Joe Onorato9c1289c2009-08-17 11:03:03 -0400958 * Make an ApplicationInfo object for a sortcut
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800959 */
Joe Onorato9c1289c2009-08-17 11:03:03 -0400960 private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
961 int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800962
Joe Onorato9c1289c2009-08-17 11:03:03 -0400963 final ApplicationInfo info = new ApplicationInfo();
964 info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800965
Joe Onorato9c1289c2009-08-17 11:03:03 -0400966 int iconType = c.getInt(iconTypeIndex);
967 switch (iconType) {
968 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
969 String packageName = c.getString(iconPackageIndex);
970 String resourceName = c.getString(iconResourceIndex);
971 PackageManager packageManager = context.getPackageManager();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800972 try {
Joe Onorato9c1289c2009-08-17 11:03:03 -0400973 Resources resources = packageManager.getResourcesForApplication(packageName);
974 final int id = resources.getIdentifier(resourceName, null, null);
975 info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context,
976 false);
977 } catch (Exception e) {
978 info.icon = packageManager.getDefaultActivityIcon();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800979 }
Joe Onorato9c1289c2009-08-17 11:03:03 -0400980 info.iconResource = new Intent.ShortcutIconResource();
981 info.iconResource.packageName = packageName;
982 info.iconResource.resourceName = resourceName;
983 info.customIcon = false;
984 break;
985 case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
986 byte[] data = c.getBlob(iconIndex);
987 try {
988 Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
989 info.icon = new FastBitmapDrawable(
990 Utilities.createBitmapThumbnail(bitmap, context));
991 } catch (Exception e) {
992 packageManager = context.getPackageManager();
993 info.icon = packageManager.getDefaultActivityIcon();
994 }
995 info.filtered = true;
996 info.customIcon = true;
997 break;
998 default:
999 info.icon = context.getPackageManager().getDefaultActivityIcon();
1000 info.customIcon = false;
1001 break;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001002 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001003 return info;
1004 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001005
Joe Onorato9c1289c2009-08-17 11:03:03 -04001006 private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
1007 int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
1008
1009 int iconType = c.getInt(iconTypeIndex);
1010 switch (iconType) {
1011 case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
1012 String packageName = c.getString(iconPackageIndex);
1013 String resourceName = c.getString(iconResourceIndex);
1014 PackageManager packageManager = context.getPackageManager();
1015 try {
1016 Resources resources = packageManager.getResourcesForApplication(packageName);
1017 final int id = resources.getIdentifier(resourceName, null, null);
1018 liveFolderInfo.icon = resources.getDrawable(id);
1019 } catch (Exception e) {
1020 liveFolderInfo.icon =
1021 context.getResources().getDrawable(R.drawable.ic_launcher_folder);
1022 }
1023 liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
1024 liveFolderInfo.iconResource.packageName = packageName;
1025 liveFolderInfo.iconResource.resourceName = resourceName;
1026 break;
1027 default:
1028 liveFolderInfo.icon =
1029 context.getResources().getDrawable(R.drawable.ic_launcher_folder);
1030 }
1031 }
1032
1033 /**
1034 * Return an existing UserFolderInfo object if we have encountered this ID previously,
1035 * or make a new one.
1036 */
1037 private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
1038 // See if a placeholder was created for us already
1039 FolderInfo folderInfo = folders.get(id);
1040 if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
1041 // No placeholder -- create a new instance
1042 folderInfo = new UserFolderInfo();
1043 folders.put(id, folderInfo);
1044 }
1045 return (UserFolderInfo) folderInfo;
1046 }
1047
1048 /**
1049 * Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
1050 * new one.
1051 */
1052 private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
1053 // See if a placeholder was created for us already
1054 FolderInfo folderInfo = folders.get(id);
1055 if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
1056 // No placeholder -- create a new instance
1057 folderInfo = new LiveFolderInfo();
1058 folders.put(id, folderInfo);
1059 }
1060 return (LiveFolderInfo) folderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001061 }
1062
1063 private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
1064 final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
Romain Guy73b979d2009-06-09 12:57:21 -07001065 new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001066 LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
1067 null, null, null);
1068
Romain Guy73b979d2009-06-09 12:57:21 -07001069 final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001070 final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
1071 final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
1072 final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
1073
1074 // boolean changed = false;
1075
1076 try {
1077 while (c.moveToNext()) {
1078 try {
1079 if (c.getInt(itemTypeIndex) !=
1080 LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
1081 continue;
1082 }
1083
1084 final String intentUri = c.getString(intentIndex);
1085 if (intentUri != null) {
Romain Guy1ce1a242009-06-23 17:34:54 -07001086 final Intent shortcut = Intent.parseUri(intentUri, 0);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001087 if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
1088 final ComponentName name = shortcut.getComponent();
1089 if (name != null) {
1090 final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
1091 final String title = c.getString(titleIndex);
1092 String label = getLabel(manager, activityInfo);
1093
1094 if (title == null || !title.equals(label)) {
1095 final ContentValues values = new ContentValues();
1096 values.put(LauncherSettings.Favorites.TITLE, label);
1097
Romain Guyfedc4fc2009-03-27 20:48:20 -07001098 resolver.update(
1099 LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001100 values, "_id=?",
1101 new String[] { String.valueOf(c.getLong(idIndex)) });
1102
1103 // changed = true;
1104 }
1105 }
1106 }
1107 }
1108 } catch (URISyntaxException e) {
1109 // Ignore
1110 } catch (PackageManager.NameNotFoundException e) {
1111 // Ignore
1112 }
1113 }
1114 } finally {
1115 c.close();
1116 }
1117
1118 // if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
1119 }
1120
1121 private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
1122 String label = activityInfo.loadLabel(manager).toString();
1123 if (label == null) {
1124 label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
1125 if (label == null) {
1126 label = activityInfo.name;
1127 }
1128 }
1129 return label;
1130 }
1131
Joe Onorato9c1289c2009-08-17 11:03:03 -04001132 private static final Collator sCollator = Collator.getInstance();
1133 private static final Comparator<ApplicationInfo> sComparator
1134 = new Comparator<ApplicationInfo>() {
1135 public final int compare(ApplicationInfo a, ApplicationInfo b) {
1136 return sCollator.compare(a.title.toString(), b.title.toString());
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001137 }
Joe Onorato9c1289c2009-08-17 11:03:03 -04001138 };
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001139}