OSDN Git Service

Updates to 3D gallery. Build 1203.
[android-x86/packages-apps-Gallery2.git] / src / com / cooliris / cache / CacheService.java
1 package com.cooliris.cache;
2
3 import java.io.BufferedInputStream;
4 import java.io.BufferedOutputStream;
5 import java.io.ByteArrayInputStream;
6 import java.io.ByteArrayOutputStream;
7 import java.io.DataInputStream;
8 import java.io.DataOutputStream;
9 import java.io.IOException;
10 import java.net.URISyntaxException;
11 import java.nio.ByteBuffer;
12 import java.nio.LongBuffer;
13 import java.text.DateFormat;
14 import java.text.ParseException;
15 import java.text.SimpleDateFormat;
16 import java.util.ArrayList;
17 import java.util.Date;
18 import java.util.Locale;
19 import java.util.concurrent.atomic.AtomicReference;
20
21 import android.app.IntentService;
22 import android.content.ContentResolver;
23 import android.content.ContentValues;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.database.Cursor;
27 import android.database.MergeCursor;
28 import android.graphics.Bitmap;
29 import android.graphics.Canvas;
30 import android.graphics.Paint;
31 import android.graphics.Rect;
32 import android.media.ExifInterface;
33 import android.net.Uri;
34 import android.os.Environment;
35 import android.os.Process;
36 import android.os.SystemClock;
37 import android.provider.MediaStore;
38 import android.provider.MediaStore.Images;
39 import android.provider.MediaStore.Video;
40 import android.util.Log;
41
42 import com.cooliris.media.DataSource;
43 import com.cooliris.media.DiskCache;
44 import com.cooliris.media.Gallery;
45 import com.cooliris.media.LocalDataSource;
46 import com.cooliris.media.LongSparseArray;
47 import com.cooliris.media.MediaFeed;
48 import com.cooliris.media.MediaItem;
49 import com.cooliris.media.MediaSet;
50 import com.cooliris.media.R;
51 import com.cooliris.media.Shared;
52 import com.cooliris.media.SortCursor;
53 import com.cooliris.media.UriTexture;
54 import com.cooliris.media.Utils;
55
56 public final class CacheService extends IntentService {
57         public static final String ACTION_CACHE = "com.cooliris.cache.action.CACHE";
58         public static final DiskCache sAlbumCache = new DiskCache("local-album-cache");
59         public static final DiskCache sMetaAlbumCache = new DiskCache("local-meta-album-cache");
60
61         private static final String TAG = "CacheService";
62         private static ImageList sList = null;
63
64         // Wait 2 seconds to start the thumbnailer so that the application can load
65         // without any overheads.
66         private static final int THUMBNAILER_WAIT_IN_MS = 2000;
67         private static final int DEFAULT_THUMBNAIL_WIDTH = 128;
68         private static final int DEFAULT_THUMBNAIL_HEIGHT = 96;
69
70         public static final String DEFAULT_IMAGE_SORT_ORDER = Images.ImageColumns.DATE_TAKEN + " ASC, "
71                 + Images.ImageColumns.DATE_ADDED + " ASC";
72         public static final String DEFAULT_VIDEO_SORT_ORDER = Video.VideoColumns.DATE_TAKEN + " ASC, " + Video.VideoColumns.DATE_ADDED
73                 + " ASC";
74         public static final String DEFAULT_BUCKET_SORT_ORDER = "upper(" + Images.ImageColumns.BUCKET_DISPLAY_NAME + ") ASC";
75
76         // Must preserve order between these indices and the order of the terms in
77         // BUCKET_PROJECTION_IMAGES, BUCKET_PROJECTION_VIDEOS.
78         // Not using SortedHashMap for efficieny reasons.
79         public static final int BUCKET_ID_INDEX = 0;
80         public static final int BUCKET_NAME_INDEX = 1;
81         public static final String[] BUCKET_PROJECTION_IMAGES = new String[] { Images.ImageColumns.BUCKET_ID,
82                 Images.ImageColumns.BUCKET_DISPLAY_NAME };
83
84         public static final String[] BUCKET_PROJECTION_VIDEOS = new String[] { Video.VideoColumns.BUCKET_ID,
85                 Video.VideoColumns.BUCKET_DISPLAY_NAME };
86
87         // Must preserve order between these indices and the order of the terms in
88         // THUMBNAIL_PROJECTION.
89         public static final int THUMBNAIL_ID_INDEX = 0;
90         public static final int THUMBNAIL_DATE_MODIFIED_INDEX = 1;
91         public static final int THUMBNAIL_DATA_INDEX = 2;
92         public static final int THUMBNAIL_ORIENTATION_INDEX = 2;
93         public static final String[] THUMBNAIL_PROJECTION = new String[] { Images.ImageColumns._ID, Images.ImageColumns.DATE_MODIFIED,
94                 Images.ImageColumns.DATA, Images.ImageColumns.ORIENTATION };
95
96         public static final String[] SENSE_PROJECTION = new String[] { Images.ImageColumns.BUCKET_ID,
97                 "MAX(" + Images.ImageColumns.DATE_ADDED + ")" };
98
99         // Must preserve order between these indices and the order of the terms in
100         // INITIAL_PROJECTION_IMAGES and
101         // INITIAL_PROJECTION_VIDEOS.
102         public static final int MEDIA_ID_INDEX = 0;
103         public static final int MEDIA_CAPTION_INDEX = 1;
104         public static final int MEDIA_MIME_TYPE_INDEX = 2;
105         public static final int MEDIA_LATITUDE_INDEX = 3;
106         public static final int MEDIA_LONGITUDE_INDEX = 4;
107         public static final int MEDIA_DATE_TAKEN_INDEX = 5;
108         public static final int MEDIA_DATE_ADDED_INDEX = 6;
109         public static final int MEDIA_DATE_MODIFIED_INDEX = 7;
110         public static final int MEDIA_DATA_INDEX = 8;
111         public static final int MEDIA_ORIENTATION_OR_DURATION_INDEX = 9;
112         public static final int MEDIA_BUCKET_ID_INDEX = 10;
113         public static final String[] PROJECTION_IMAGES = new String[] { Images.ImageColumns._ID, Images.ImageColumns.TITLE,
114                 Images.ImageColumns.MIME_TYPE, Images.ImageColumns.LATITUDE, Images.ImageColumns.LONGITUDE,
115                 Images.ImageColumns.DATE_TAKEN, Images.ImageColumns.DATE_ADDED, Images.ImageColumns.DATE_MODIFIED,
116                 Images.ImageColumns.DATA, Images.ImageColumns.ORIENTATION, Images.ImageColumns.BUCKET_ID };
117
118         private static final String[] PROJECTION_VIDEOS = new String[] { Video.VideoColumns._ID, Video.VideoColumns.TITLE,
119                 Video.VideoColumns.MIME_TYPE, Video.VideoColumns.LATITUDE, Video.VideoColumns.LONGITUDE, Video.VideoColumns.DATE_TAKEN,
120                 Video.VideoColumns.DATE_ADDED, Video.VideoColumns.DATE_MODIFIED, Video.VideoColumns.DATA, Video.VideoColumns.DURATION,
121                 Video.VideoColumns.BUCKET_ID };
122
123         public static final String BASE_CONTENT_STRING_IMAGES = (Images.Media.EXTERNAL_CONTENT_URI).toString() + "/";
124         public static final String BASE_CONTENT_STRING_VIDEOS = (Video.Media.EXTERNAL_CONTENT_URI).toString() + "/";
125         private static final AtomicReference<Thread> CACHE_THREAD = new AtomicReference<Thread>();
126         private static final AtomicReference<Thread> THUMBNAIL_THREAD = new AtomicReference<Thread>();
127
128         // Special indices in the Albumcache.
129         private static final int ALBUM_CACHE_METADATA_INDEX = -1;
130         private static final int ALBUM_CACHE_DIRTY_INDEX = -2;
131         private static final int ALBUM_CACHE_INCOMPLETE_INDEX = -3;
132         private static final int ALBUM_CACHE_DIRTY_BUCKET_INDEX = -4;
133         private static final int ALBUM_CACHE_LOCALE_INDEX = -5;
134
135         private static final DateFormat mDateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
136         private static final DateFormat mAltDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
137         private static final byte[] sDummyData = new byte[] { 1 };
138         private static boolean QUEUE_DIRTY_SET;
139         private static boolean QUEUE_DIRTY_ALL;
140         private static boolean QUEUE_DIRTY_SENSE;
141
142         public interface Observer {
143                 void onChange(long[] bucketIds);
144         }
145
146         public static final String getCachePath(final String subFolderName) {
147                 return Environment.getExternalStorageDirectory() + "/Android/data/com.cooliris.media/cache/" + subFolderName;
148         }
149
150         public static final void startCache(final Context context, final boolean checkthumbnails) {
151                 final Locale locale = getLocaleForAlbumCache();
152                 final Locale defaultLocale = Locale.getDefault();
153                 if (locale == null || !locale.equals(defaultLocale)) {
154                         sAlbumCache.deleteAll();
155                         putLocaleForAlbumCache(defaultLocale);
156                 }
157                 final Intent intent = new Intent(ACTION_CACHE, null, context, CacheService.class);
158                 intent.putExtra("checkthumbnails", checkthumbnails);
159                 context.startService(intent);
160         }
161
162         public static final boolean isCacheReady(final boolean onlyMediaSets) {
163                 if (onlyMediaSets) {
164                         return (sAlbumCache.get(ALBUM_CACHE_METADATA_INDEX, 0) != null && sAlbumCache.get(ALBUM_CACHE_DIRTY_INDEX, 0) == null);
165                 } else {
166                         return (sAlbumCache.get(ALBUM_CACHE_METADATA_INDEX, 0) != null && sAlbumCache.get(ALBUM_CACHE_DIRTY_INDEX, 0) == null && sAlbumCache
167                                 .get(ALBUM_CACHE_INCOMPLETE_INDEX, 0) == null);
168                 }
169         }
170
171         public static final boolean isCacheReady(final long setId) {
172                 final boolean isReady = (sAlbumCache.get(ALBUM_CACHE_METADATA_INDEX, 0) != null
173                         && sAlbumCache.get(ALBUM_CACHE_DIRTY_INDEX, 0) == null && sAlbumCache.get(ALBUM_CACHE_INCOMPLETE_INDEX, 0) == null);
174                 if (!isReady) {
175                         return isReady;
176                 }
177                 // Also, we need to check if this setId is dirty.
178                 final byte[] existingData = sAlbumCache.get(ALBUM_CACHE_DIRTY_BUCKET_INDEX, 0);
179                 if (existingData != null && existingData.length > 0) {
180                         final long[] ids = toLongArray(existingData);
181                         final int numIds = ids.length;
182                         for (int i = 0; i < numIds; ++i) {
183                                 if (ids[i] == setId) {
184                                         return false;
185                                 }
186                         }
187                 }
188                 return true;
189         }
190
191         public static final boolean isPresentInCache(final long setId) {
192                 return sAlbumCache.get(setId, 0) != null;
193         }
194
195         public static final void senseDirty(final Context context, final Observer observer) {
196                 if (CACHE_THREAD.get() == null) {
197                         QUEUE_DIRTY_SENSE = false;
198                         QUEUE_DIRTY_ALL = false;
199                         QUEUE_DIRTY_SET = false;
200                         restartThread(CACHE_THREAD, "CacheRefresh", new Runnable() {
201                                 public void run() {
202                                         Log.i(TAG, "Computing dirty sets.");
203                                         long ids[] = computeDirtySets(context);
204                                         if (ids != null && observer != null) {
205                                                 observer.onChange(ids);
206                                         }
207                                         if (ids.length > 0) {
208                                                 sList = null;
209                                         }
210                                         Log.i(TAG, "Done computing dirty sets for num " + ids.length);
211                                 }
212                         });
213                 } else {
214                         QUEUE_DIRTY_SENSE = true;
215                 }
216         }
217
218         public static final void markDirty(final Context context) {
219                 sList = null;
220                 sAlbumCache.put(ALBUM_CACHE_DIRTY_INDEX, sDummyData);
221                 if (CACHE_THREAD.get() == null) {
222                         QUEUE_DIRTY_SENSE = false;
223                         QUEUE_DIRTY_ALL = false;
224                         QUEUE_DIRTY_SET = false;
225                         restartThread(CACHE_THREAD, "CacheRefresh", new Runnable() {
226                                 public void run() {
227                                         refresh(context);
228                                 }
229                         });
230                 } else {
231                         QUEUE_DIRTY_ALL = true;
232                 }
233         }
234
235         public static final void markDirtyImmediate(final long id) {
236                 if (id == Shared.INVALID) {
237                         return;
238                 }
239                 sList = null;
240                 byte[] data = longToByteArray(id);
241                 final byte[] existingData = sAlbumCache.get(ALBUM_CACHE_DIRTY_BUCKET_INDEX, 0);
242                 if (existingData != null && existingData.length > 0) {
243                         final long[] ids = toLongArray(existingData);
244                         final int numIds = ids.length;
245                         for (int i = 0; i < numIds; ++i) {
246                                 if (ids[i] == id) {
247                                         return;
248                                 }
249                         }
250                         // Add this to the existing keys and concatenate the byte arrays.
251                         data = concat(data, existingData);
252                 }
253                 sAlbumCache.put(ALBUM_CACHE_DIRTY_BUCKET_INDEX, data);
254         }
255
256         public static final void markDirty(final Context context, final long id) {
257                 markDirtyImmediate(id);
258                 if (CACHE_THREAD.get() == null) {
259                         QUEUE_DIRTY_SET = false;
260                         restartThread(CACHE_THREAD, "CacheRefreshDirtySets", new Runnable() {
261                                 public void run() {
262                                         refreshDirtySets(context);
263                                 }
264                         });
265                 } else {
266                         QUEUE_DIRTY_SET = true;
267                 }
268         }
269
270         public static final boolean setHasItems(final ContentResolver cr, final long setId) {
271                 final Uri uriImages = Images.Media.EXTERNAL_CONTENT_URI;
272                 final Uri uriVideos = Video.Media.EXTERNAL_CONTENT_URI;
273                 final StringBuffer whereString = new StringBuffer(Images.ImageColumns.BUCKET_ID + "=" + setId);
274                 final Cursor cursorImages = cr.query(uriImages, BUCKET_PROJECTION_IMAGES, whereString.toString(), null, null);
275                 if (cursorImages != null && cursorImages.getCount() > 0) {
276                         cursorImages.close();
277                         return true;
278                 }
279                 final Cursor cursorVideos = cr.query(uriVideos, BUCKET_PROJECTION_VIDEOS, whereString.toString(), null, null);
280                 if (cursorVideos != null && cursorVideos.getCount() > 0) {
281                         cursorVideos.close();
282                         return true;
283                 }
284                 return false;
285         }
286
287         public static final void loadMediaSets(final MediaFeed feed, final DataSource source, final boolean includeImages,
288                 final boolean includeVideos) {
289                 int timeElapsed = 0;
290                 while (!isCacheReady(true) && timeElapsed < 10000) {
291                         try {
292                                 Thread.sleep(300);
293                         } catch (InterruptedException e) {
294                                 return;
295                         }
296                         timeElapsed += 300;
297                 }
298                 final byte[] albumData = sAlbumCache.get(ALBUM_CACHE_METADATA_INDEX, 0);
299                 if (albumData != null && albumData.length > 0) {
300                         final DataInputStream dis = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(albumData), 256));
301                         try {
302                                 final int numAlbums = dis.readInt();
303                                 for (int i = 0; i < numAlbums; ++i) {
304                                         final long setId = dis.readLong();
305                                         final String name = Utils.readUTF(dis);
306                                         final boolean hasImages = dis.readBoolean();
307                                         final boolean hasVideos = dis.readBoolean();
308                                         MediaSet mediaSet = feed.getMediaSet(setId);
309                                         if (mediaSet == null) {
310                                                 mediaSet = feed.addMediaSet(setId, source);
311                                         }
312                                         if ((includeImages && hasImages) || (includeVideos && hasVideos)) {
313                                                 mediaSet.mName = name;
314                                                 mediaSet.mHasImages = hasImages;
315                                                 mediaSet.mHasVideos = hasVideos;
316                                                 mediaSet.mPicasaAlbumId = Shared.INVALID;
317                                                 mediaSet.generateTitle(true);
318                                         }
319                                 }
320                         } catch (IOException e) {
321                                 Log.e(TAG, "Error loading albums.");
322                                 sAlbumCache.deleteAll();
323                                 putLocaleForAlbumCache(Locale.getDefault());
324                         }
325                 } else {
326                         Log.d(TAG, "No albums found.");
327                 }
328         }
329
330         public static final void loadMediaSet(final MediaFeed feed, final DataSource source, final long bucketId) {
331                 int timeElapsed = 0;
332                 while (!isCacheReady(false) && timeElapsed < 10000) {
333                         try {
334                                 Thread.sleep(300);
335                         } catch (InterruptedException e) {
336                                 return;
337                         }
338                         timeElapsed += 300;
339                 }
340                 final byte[] albumData = sAlbumCache.get(ALBUM_CACHE_METADATA_INDEX, 0);
341                 if (albumData != null && albumData.length > 0) {
342                         DataInputStream dis = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(albumData), 256));
343                         try {
344                                 final int numAlbums = dis.readInt();
345                                 for (int i = 0; i < numAlbums; ++i) {
346                                         final long setId = dis.readLong();
347                                         MediaSet mediaSet = null;
348                                         if (setId == bucketId) {
349                                                 mediaSet = feed.getMediaSet(setId);
350                                                 if (mediaSet == null) {
351                                                         mediaSet = feed.addMediaSet(setId, source);
352                                                 }
353                                         } else {
354                                                 mediaSet = new MediaSet();
355                                         }
356                                         mediaSet.mName = Utils.readUTF(dis);
357                                         if (setId == bucketId) {
358                                                 mediaSet.mPicasaAlbumId = Shared.INVALID;
359                                                 mediaSet.generateTitle(true);
360                                                 return;
361                                         }
362                                 }
363                         } catch (IOException e) {
364                                 Log.e(TAG, "Error finding album " + bucketId);
365                                 sAlbumCache.deleteAll();
366                                 putLocaleForAlbumCache(Locale.getDefault());
367                         }
368                 } else {
369                         Log.d(TAG, "No album found for album id " + bucketId);
370                 }
371         }
372
373         public static final void loadMediaItemsIntoMediaFeed(final MediaFeed feed, final MediaSet set, final int rangeStart,
374                 final int rangeEnd, final boolean includeImages, final boolean includeVideos) {
375                 int timeElapsed = 0;
376                 byte[] albumData = null;
377                 while (!isCacheReady(set.mId) && timeElapsed < 30000) {
378                         try {
379                                 Thread.sleep(300);
380                         } catch (InterruptedException e) {
381                                 return;
382                         }
383                         timeElapsed += 300;
384                 }
385                 albumData = sAlbumCache.get(set.mId, 0);
386                 if (albumData != null && set.mNumItemsLoaded < set.getNumExpectedItems()) {
387                         final DataInputStream dis = new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(albumData), 256));
388                         try {
389                                 final int numItems = dis.readInt();
390                                 set.setNumExpectedItems(numItems);
391                                 set.mMinTimestamp = dis.readLong();
392                                 set.mMaxTimestamp = dis.readLong();
393                                 for (int i = 0; i < numItems; ++i) {
394                                         final MediaItem item = new MediaItem();
395                                         // Must preserve order with method that writes to cache.
396                                         item.mId = dis.readLong();
397                                         item.mCaption = Utils.readUTF(dis);
398                                         item.mMimeType = Utils.readUTF(dis);
399                                         item.setMediaType(dis.readInt());
400                                         item.mLatitude = dis.readDouble();
401                                         item.mLongitude = dis.readDouble();
402                                         item.mDateTakenInMs = dis.readLong();
403                                         item.mTriedRetrievingExifDateTaken = dis.readBoolean();
404                                         item.mDateAddedInSec = dis.readLong();
405                                         item.mDateModifiedInSec = dis.readLong();
406                                         item.mDurationInSec = dis.readInt();
407                                         item.mRotation = (float) dis.readInt();
408                                         item.mFilePath = Utils.readUTF(dis);
409                                         int itemMediaType = item.getMediaType();
410                                         if ((itemMediaType == MediaItem.MEDIA_TYPE_IMAGE && includeImages)
411                                                 || (itemMediaType == MediaItem.MEDIA_TYPE_VIDEO && includeVideos)) {
412                                                 String baseUri = (itemMediaType == MediaItem.MEDIA_TYPE_IMAGE) ? BASE_CONTENT_STRING_IMAGES
413                                                         : BASE_CONTENT_STRING_VIDEOS;
414                                                 item.mContentUri = baseUri + item.mId;
415                                                 feed.addItemToMediaSet(item, set);
416                                         }
417                                 }
418                                 dis.close();
419                         } catch (IOException e) {
420                                 Log.e(TAG, "Error loading items for album " + set.mName);
421                                 sAlbumCache.deleteAll();
422                                 putLocaleForAlbumCache(Locale.getDefault());
423                         }
424                 } else {
425                         Log.d(TAG, "No items found for album " + set.mName);
426                 }
427                 set.updateNumExpectedItems();
428                 set.generateTitle(true);
429         }
430
431         public static final void populateVideoItemFromCursor(final MediaItem item, final ContentResolver cr, final Cursor cursor,
432                 final String baseUri) {
433                 item.setMediaType(MediaItem.MEDIA_TYPE_VIDEO);
434                 populateMediaItemFromCursor(item, cr, cursor, baseUri);
435         }
436
437         public static final void populateMediaItemFromCursor(final MediaItem item, final ContentResolver cr, final Cursor cursor,
438                 final String baseUri) {
439                 item.mId = cursor.getLong(CacheService.MEDIA_ID_INDEX);
440                 item.mCaption = cursor.getString(CacheService.MEDIA_CAPTION_INDEX);
441                 item.mMimeType = cursor.getString(CacheService.MEDIA_MIME_TYPE_INDEX);
442                 item.mLatitude = cursor.getDouble(CacheService.MEDIA_LATITUDE_INDEX);
443                 item.mLongitude = cursor.getDouble(CacheService.MEDIA_LONGITUDE_INDEX);
444                 item.mDateTakenInMs = cursor.getLong(CacheService.MEDIA_DATE_TAKEN_INDEX);
445                 item.mDateAddedInSec = cursor.getLong(CacheService.MEDIA_DATE_ADDED_INDEX);
446                 item.mDateModifiedInSec = cursor.getLong(CacheService.MEDIA_DATE_MODIFIED_INDEX);
447                 if (item.mDateTakenInMs == item.mDateModifiedInSec) {
448                         item.mDateTakenInMs = item.mDateModifiedInSec * 1000;
449                 }
450                 item.mFilePath = cursor.getString(CacheService.MEDIA_DATA_INDEX);
451                 if (baseUri != null)
452                         item.mContentUri = baseUri + item.mId;
453                 final int itemMediaType = item.getMediaType();
454                 // Check to see if a new date taken is available.
455                 final long dateTaken = fetchDateTaken(item);
456                 if (dateTaken != -1L && item.mContentUri != null) {
457                         item.mDateTakenInMs = dateTaken;
458                         final ContentValues values = new ContentValues();
459                         if (itemMediaType == MediaItem.MEDIA_TYPE_VIDEO) {
460                                 values.put(Video.VideoColumns.DATE_TAKEN, item.mDateTakenInMs);
461                         } else {
462                                 values.put(Images.ImageColumns.DATE_TAKEN, item.mDateTakenInMs);
463                         }
464                         cr.update(Uri.parse(item.mContentUri), values, null, null);
465                 }
466
467                 final int orientationDurationValue = cursor.getInt(CacheService.MEDIA_ORIENTATION_OR_DURATION_INDEX);
468                 if (itemMediaType == MediaItem.MEDIA_TYPE_IMAGE) {
469                         item.mRotation = orientationDurationValue;
470                 } else {
471                         item.mDurationInSec = orientationDurationValue;
472                 }
473         }
474
475         // Returns -1 if we failed to examine EXIF information or EXIF parsing
476         // failed.
477         public static final long fetchDateTaken(final MediaItem item) {
478                 if (!item.isDateTakenValid() && !item.mTriedRetrievingExifDateTaken
479                         && (item.mFilePath.endsWith(".jpg") || item.mFilePath.endsWith(".jpeg"))) {
480                         try {
481                                 Log.i(TAG, "Parsing date taken from exif");
482                                 final ExifInterface exif = new ExifInterface(item.mFilePath);
483                                 final String dateTakenStr = exif.getAttribute(ExifInterface.TAG_DATETIME);
484                                 if (dateTakenStr != null) {
485                                         try {
486                                                 final Date dateTaken = mDateFormat.parse(dateTakenStr);
487                                                 return dateTaken.getTime();
488                                         } catch (ParseException pe) {
489                                                 try {
490                                                         final Date dateTaken = mAltDateFormat.parse(dateTakenStr);
491                                                         return dateTaken.getTime();
492                                                 } catch (ParseException pe2) {
493                                                         Log.i(TAG, "Unable to parse date out of string - " + dateTakenStr);
494                                                 }
495                                         }
496                                 }
497                         } catch (Exception e) {
498                                 Log.i(TAG, "Error reading Exif information, probably not a jpeg.");
499                         }
500
501                         // Ensures that we only try retrieving EXIF date taken once.
502                         item.mTriedRetrievingExifDateTaken = true;
503                 }
504                 return -1L;
505         }
506
507         public static final byte[] queryThumbnail(final Context context, final long thumbId, final long origId, final boolean isVideo,
508                 final long timestamp) {
509                 final DiskCache thumbnailCache = (isVideo) ? LocalDataSource.sThumbnailCacheVideo : LocalDataSource.sThumbnailCache;
510                 return queryThumbnail(context, thumbId, origId, isVideo, thumbnailCache, timestamp);
511         }
512
513         public static final ImageList getImageList(final Context context) {
514                 if (sList != null)
515                         return sList;
516                 ImageList list = new ImageList();
517                 final Uri uriImages = Images.Media.EXTERNAL_CONTENT_URI;
518                 final ContentResolver cr = context.getContentResolver();
519                 final Cursor cursorImages = cr.query(uriImages, THUMBNAIL_PROJECTION, null, null, null);
520                 if (cursorImages != null && cursorImages.moveToFirst()) {
521                         final int size = cursorImages.getCount();
522                         final long[] ids = new long[size];
523                         final long[] thumbnailIds = new long[size];
524                         final long[] timestamp = new long[size];
525                         final int[] orientation = new int[size];
526                         int ctr = 0;
527                         do {
528                                 if (Thread.interrupted()) {
529                                         break;
530                                 }
531                                 ids[ctr] = cursorImages.getLong(THUMBNAIL_ID_INDEX);
532                                 timestamp[ctr] = cursorImages.getLong(THUMBNAIL_DATE_MODIFIED_INDEX);
533                                 thumbnailIds[ctr] = Utils.Crc64Long(cursorImages.getString(THUMBNAIL_DATA_INDEX));
534                                 orientation[ctr] = cursorImages.getInt(THUMBNAIL_ORIENTATION_INDEX);
535                                 ++ctr;
536                         } while (cursorImages.moveToNext());
537                         cursorImages.close();
538                         list.ids = ids;
539                         list.thumbids = thumbnailIds;
540                         list.timestamp = timestamp;
541                         list.orientation = orientation;
542                 }
543                 if (sList == null) {
544                         sList = list;
545                 }
546                 return list;
547         }
548
549         private static final byte[] queryThumbnail(final Context context, final long thumbId, final long origId, final boolean isVideo,
550                 final DiskCache thumbnailCache, final long timestamp) {
551                 if (!((Gallery) context).isPaused()) {
552                         final Thread thumbnailThread = THUMBNAIL_THREAD.getAndSet(null);
553                         if (thumbnailThread != null) {
554                                 thumbnailThread.interrupt();
555                         }
556                 }
557                 byte[] bitmap = thumbnailCache.get(thumbId, timestamp);
558                 if (bitmap == null) {
559                         Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
560                         final long time = SystemClock.uptimeMillis();
561                         bitmap = buildThumbnailForId(context, thumbnailCache, thumbId, origId, isVideo, DEFAULT_THUMBNAIL_WIDTH,
562                                 DEFAULT_THUMBNAIL_HEIGHT);
563                         Log.i(TAG, "Built thumbnail and screennail for " + origId + " in " + (SystemClock.uptimeMillis() - time));
564                         Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
565                 }
566                 return bitmap;
567         }
568
569         private static final void buildThumbnails(final Context context) {
570                 Log.i(TAG, "Preparing DiskCache for all thumbnails.");
571                 ImageList list = getImageList(context);
572                 final int size = (list.ids == null) ? 0 : list.ids.length;
573                 final long[] ids = list.ids;
574                 final long[] timestamp = list.timestamp;
575                 final long[] thumbnailIds = list.thumbids;
576                 final DiskCache thumbnailCache = LocalDataSource.sThumbnailCache;
577                 for (int i = 0; i < size; ++i) {
578                         if (Thread.interrupted()) {
579                                 return;
580                         }
581                         final long id = ids[i];
582                         final long timeModifiedInSec = timestamp[i];
583                         final long thumbnailId = thumbnailIds[i];
584                         if (!thumbnailCache.isDataAvailable(thumbnailId, timeModifiedInSec * 1000)) {
585                                 buildThumbnailForId(context, thumbnailCache, thumbnailId, id, false, DEFAULT_THUMBNAIL_WIDTH,
586                                         DEFAULT_THUMBNAIL_HEIGHT);
587                         }
588                 }
589                 Log.i(TAG, "DiskCache ready for all thumbnails.");
590         }
591
592         private static final byte[] buildThumbnailForId(final Context context, final DiskCache thumbnailCache, final long thumbId,
593                 final long origId, final boolean isVideo, final int thumbnailWidth, final int thumbnailHeight) {
594                 if (origId == Shared.INVALID) {
595                         return null;
596                 }
597                 try {
598                         Bitmap bitmap = null;
599                         Thread.sleep(1);
600                         if (!isVideo) {
601                                 final String uriString = BASE_CONTENT_STRING_IMAGES + origId;
602                                 UriTexture.invalidateCache(thumbId, 1024);
603                                 try {
604                                         bitmap = UriTexture.createFromUri(context, uriString, 1024, 1024, thumbId, null);
605                                 } catch (IOException e) {
606                                         return null;
607                                 } catch (URISyntaxException e) {
608                                         return null;
609                                 }
610                         } else {
611                                 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
612                                 new Thread() {
613                                         public void run() {
614                                                 try {
615                                                         Thread.sleep(5000);
616                                                 } catch (InterruptedException e) {
617                                                         ;
618                                                 }
619                                                 try {
620                                                         MediaStore.Video.Thumbnails.cancelThumbnailRequest(context.getContentResolver(), origId);
621                                                 } catch (Exception e) {
622                                                         ;
623                                                 }
624                                         }
625                                 }.start();
626                                 bitmap = MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(), origId,
627                                         MediaStore.Video.Thumbnails.MICRO_KIND, null);
628                         }
629                         if (bitmap == null) {
630                                 return null;
631                         }
632                         final byte[] retVal = writeBitmapToCache(thumbnailCache, thumbId, origId, bitmap, thumbnailWidth, thumbnailHeight);
633                         return retVal;
634                 } catch (InterruptedException e) {
635                         return null;
636                 }
637         }
638
639         public static final byte[] writeBitmapToCache(final DiskCache thumbnailCache, final long thumbId, final long origId,
640                 final Bitmap bitmap, final int thumbnailWidth, final int thumbnailHeight) {
641                 final int width = bitmap.getWidth();
642                 final int height = bitmap.getHeight();
643                 // Detect faces to find the focal point, otherwise fall back to the
644                 // image center.
645                 int focusX = width / 2;
646                 int focusY = height / 2;
647                 // We have commented out face detection since it slows down the
648                 // generation of the thumbnail and screennail.
649
650                 // final FaceDetector faceDetector = new FaceDetector(width, height, 1);
651                 // final FaceDetector.Face[] faces = new FaceDetector.Face[1];
652                 // final int numFaces = faceDetector.findFaces(bitmap, faces);
653                 // if (numFaces > 0 && faces[0].confidence() >=
654                 // FaceDetector.Face.CONFIDENCE_THRESHOLD) {
655                 // final PointF midPoint = new PointF();
656                 // faces[0].getMidPoint(midPoint);
657                 // focusX = (int) midPoint.x;
658                 // focusY = (int) midPoint.y;
659                 // }
660
661                 // Crop to thumbnail aspect ratio biased towards the focus point.
662                 int cropX;
663                 int cropY;
664                 int cropWidth;
665                 int cropHeight;
666                 float scaleFactor;
667                 if (thumbnailWidth * height < thumbnailHeight * width) {
668                         // Vertically constrained.
669                         cropWidth = thumbnailWidth * height / thumbnailHeight;
670                         cropX = Math.max(0, Math.min(focusX - cropWidth / 2, width - cropWidth));
671                         cropY = 0;
672                         cropHeight = height;
673                         scaleFactor = (float) thumbnailHeight / height;
674                 } else {
675                         // Horizontally constrained.
676                         cropHeight = thumbnailHeight * width / thumbnailWidth;
677                         cropY = Math.max(0, Math.min(focusY - cropHeight / 2, height - cropHeight));
678                         cropX = 0;
679                         cropWidth = width;
680                         scaleFactor = (float) thumbnailWidth / width;
681                 }
682                 final Bitmap finalBitmap = Bitmap.createBitmap(thumbnailWidth, thumbnailHeight, Bitmap.Config.RGB_565);
683                 final Canvas canvas = new Canvas(finalBitmap);
684                 final Paint paint = new Paint();
685                 paint.setFilterBitmap(true);
686                 canvas.drawColor(0);
687                 canvas.drawBitmap(bitmap, new Rect(cropX, cropY, cropX + cropWidth, cropY + cropHeight), new Rect(0, 0, thumbnailWidth,
688                         thumbnailHeight), paint);
689                 bitmap.recycle();
690
691                 // Store (long thumbnailId, short focusX, short focusY, JPEG data).
692                 final ByteArrayOutputStream cacheOutput = new ByteArrayOutputStream(16384);
693                 final DataOutputStream dataOutput = new DataOutputStream(cacheOutput);
694                 byte[] retVal = null;
695                 try {
696                         dataOutput.writeLong(origId);
697                         dataOutput.writeShort((int) ((focusX - cropX) * scaleFactor));
698                         dataOutput.writeShort((int) ((focusY - cropY) * scaleFactor));
699                         dataOutput.flush();
700                         finalBitmap.compress(Bitmap.CompressFormat.JPEG, 80, cacheOutput);
701                         retVal = cacheOutput.toByteArray();
702                         synchronized (thumbnailCache) {
703                                 thumbnailCache.put(thumbId, retVal);
704                         }
705                         cacheOutput.close();
706                 } catch (Exception e) {
707                         ;
708                 }
709                 return retVal;
710         }
711
712         public CacheService() {
713                 super("CacheService");
714         }
715
716         @Override
717         protected void onHandleIntent(final Intent intent) {
718                 Log.i(TAG, "Starting CacheService");
719                 if (Environment.getExternalStorageState() == Environment.MEDIA_BAD_REMOVAL) {
720                         sAlbumCache.deleteAll();
721                         putLocaleForAlbumCache(Locale.getDefault());
722                 }
723                 Locale locale = getLocaleForAlbumCache();
724                 if (locale != null && locale.equals(Locale.getDefault())) {
725                         // The cache is in the same locale as the system locale.
726                         if (!isCacheReady(false)) {
727                                 // The albums and their items have not yet been cached, we need
728                                 // to run the service.
729                                 startNewCacheThread();
730                         } else {
731                                 startNewCacheThreadForDirtySets();
732                         }
733                 } else {
734                         // The locale has changed, we need to regenerate the strings.
735                         sAlbumCache.deleteAll();
736                         putLocaleForAlbumCache(Locale.getDefault());
737                         startNewCacheThread();
738                 }
739                 if (intent.getBooleanExtra("checkthumbnails", false)) {
740                         startNewThumbnailThread(this);
741                 } else {
742                         final Thread existingThread = THUMBNAIL_THREAD.getAndSet(null);
743                         if (existingThread != null) {
744                                 existingThread.interrupt();
745                         }
746                 }
747         }
748
749         private static final void putLocaleForAlbumCache(final Locale locale) {
750                 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
751                 final DataOutputStream dos = new DataOutputStream(bos);
752                 try {
753                         Utils.writeUTF(dos, locale.getCountry());
754                         Utils.writeUTF(dos, locale.getLanguage());
755                         Utils.writeUTF(dos, locale.getVariant());
756                         dos.flush();
757                         bos.flush();
758                         final byte[] data = bos.toByteArray();
759                         sAlbumCache.put(ALBUM_CACHE_LOCALE_INDEX, data);
760                         sAlbumCache.flush();
761                         dos.close();
762                         bos.close();
763                 } catch (IOException e) {
764                         // Could not write locale to cache.
765                         Log.i(TAG, "Error writing locale to cache.");
766                         ;
767                 }
768         }
769
770         private static final Locale getLocaleForAlbumCache() {
771                 final byte[] data = sAlbumCache.get(ALBUM_CACHE_LOCALE_INDEX, 0);
772                 if (data != null && data.length > 0) {
773                         ByteArrayInputStream bis = new ByteArrayInputStream(data);
774                         DataInputStream dis = new DataInputStream(bis);
775                         try {
776                                 String country = Utils.readUTF(dis);
777                                 if (country == null)
778                                         country = "";
779                                 String language = Utils.readUTF(dis);
780                                 if (language == null)
781                                         language = "";
782                                 String variant = Utils.readUTF(dis);
783                                 if (variant == null)
784                                         variant = "";
785                                 final Locale locale = new Locale(language, country, variant);
786                                 dis.close();
787                                 bis.close();
788                                 return locale;
789                         } catch (IOException e) {
790                                 // Could not read locale in cache.
791                                 Log.i(TAG, "Error reading locale from cache.");
792                                 return null;
793                         }
794                 }
795                 return null;
796         }
797
798         private static final void restartThread(final AtomicReference<Thread> threadRef, final String name, final Runnable action) {
799                 // Create a new thread.
800                 final Thread newThread = new Thread() {
801                         public void run() {
802                                 try {
803                                         action.run();
804                                 } finally {
805                                         threadRef.compareAndSet(this, null);
806                                 }
807                         }
808                 };
809                 newThread.setName(name);
810                 newThread.start();
811
812                 // Interrupt any existing thread.
813                 final Thread existingThread = threadRef.getAndSet(newThread);
814                 if (existingThread != null) {
815                         existingThread.interrupt();
816                 }
817         }
818
819         public static final void startNewThumbnailThread(final Context context) {
820                 restartThread(THUMBNAIL_THREAD, "ThumbnailRefresh", new Runnable() {
821                         public void run() {
822                                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
823                                 try {
824                                         // It is an optimization to prevent the thumbnailer from
825                                         // running while the application loads
826                                         Thread.sleep(THUMBNAILER_WAIT_IN_MS);
827                                 } catch (InterruptedException e) {
828                                         return;
829                                 }
830                                 CacheService.buildThumbnails(context);
831                         }
832                 });
833         }
834
835         private void startNewCacheThread() {
836                 restartThread(CACHE_THREAD, "CacheRefresh", new Runnable() {
837                         public void run() {
838                                 refresh(CacheService.this);
839                         }
840                 });
841         }
842
843         private void startNewCacheThreadForDirtySets() {
844                 restartThread(CACHE_THREAD, "CacheRefreshDirtySets", new Runnable() {
845                         public void run() {
846                                 refreshDirtySets(CacheService.this);
847                         }
848                 });
849         }
850
851         private static final byte[] concat(final byte[] A, final byte[] B) {
852                 final byte[] C = (byte[]) new byte[A.length + B.length];
853                 System.arraycopy(A, 0, C, 0, A.length);
854                 System.arraycopy(B, 0, C, A.length, B.length);
855                 return C;
856         }
857
858         private static final long toLong(final byte[] data) {
859                 // 8 bytes for a long
860                 if (data == null || data.length < 8)
861                         return 0;
862                 final ByteBuffer bBuffer = ByteBuffer.wrap(data);
863                 final LongBuffer lBuffer = bBuffer.asLongBuffer();
864                 final int numLongs = lBuffer.capacity();
865                 return lBuffer.get(0);
866         }
867
868         private static final long[] toLongArray(final byte[] data) {
869                 final ByteBuffer bBuffer = ByteBuffer.wrap(data);
870                 final LongBuffer lBuffer = bBuffer.asLongBuffer();
871                 final int numLongs = lBuffer.capacity();
872                 final long[] retVal = new long[numLongs];
873                 for (int i = 0; i < numLongs; ++i) {
874                         retVal[i] = lBuffer.get(i);
875                 }
876                 return retVal;
877         }
878
879         private static final byte[] longToByteArray(final long l) {
880                 final byte[] bArray = new byte[8];
881                 final ByteBuffer bBuffer = ByteBuffer.wrap(bArray);
882                 final LongBuffer lBuffer = bBuffer.asLongBuffer();
883                 lBuffer.put(0, l);
884                 return bArray;
885         }
886
887         private final static void refresh(final Context context) {
888                 // First we build the album cache.
889                 // This is the meta-data about the albums / buckets on the SD card.
890                 Log.i(TAG, "Refreshing cache.");
891                 int priority = Process.getThreadPriority(Process.myTid());
892                 Process.setThreadPriority(Process.THREAD_PRIORITY_MORE_FAVORABLE);
893                 sAlbumCache.deleteAll();
894                 putLocaleForAlbumCache(Locale.getDefault());
895
896                 final ArrayList<MediaSet> sets = new ArrayList<MediaSet>();
897                 LongSparseArray<MediaSet> acceleratedSets = new LongSparseArray<MediaSet>();
898                 Log.i(TAG, "Building albums.");
899                 final Uri uriImages = Images.Media.EXTERNAL_CONTENT_URI.buildUpon().appendQueryParameter("distinct", "true").build();
900                 final Uri uriVideos = Video.Media.EXTERNAL_CONTENT_URI.buildUpon().appendQueryParameter("distinct", "true").build();
901                 final ContentResolver cr = context.getContentResolver();
902
903                 final Cursor cursorImages = cr.query(uriImages, BUCKET_PROJECTION_IMAGES, null, null, DEFAULT_BUCKET_SORT_ORDER);
904                 final Cursor cursorVideos = cr.query(uriVideos, BUCKET_PROJECTION_VIDEOS, null, null, DEFAULT_BUCKET_SORT_ORDER);
905                 Cursor[] cursors = new Cursor[2];
906                 cursors[0] = cursorImages;
907                 cursors[1] = cursorVideos;
908                 final SortCursor sortCursor = new SortCursor(cursors, Images.ImageColumns.BUCKET_DISPLAY_NAME, SortCursor.TYPE_STRING, true);
909                 try {
910                         if (sortCursor != null && sortCursor.moveToFirst()) {
911                                 sets.ensureCapacity(sortCursor.getCount());
912                                 acceleratedSets = new LongSparseArray<MediaSet>(sortCursor.getCount());
913                                 MediaSet cameraSet = new MediaSet();
914                                 cameraSet.mId = LocalDataSource.CAMERA_BUCKET_ID;
915                                 cameraSet.mName = context.getResources().getString(R.string.camera);
916                                 sets.add(cameraSet);
917                                 acceleratedSets.put(cameraSet.mId, cameraSet);
918                                 do {
919                                         if (Thread.interrupted()) {
920                                                 return;
921                                         }
922                                         long setId = sortCursor.getLong(BUCKET_ID_INDEX);
923                                         MediaSet mediaSet = findSet(setId, acceleratedSets);
924                                         if (mediaSet == null) {
925                                                 mediaSet = new MediaSet();
926                                                 mediaSet.mId = setId;
927                                                 mediaSet.mName = sortCursor.getString(BUCKET_NAME_INDEX);
928                                                 sets.add(mediaSet);
929                                                 acceleratedSets.put(setId, mediaSet);
930                                         }
931                                         mediaSet.mHasImages |= (sortCursor.getCurrentCursorIndex() == 0);
932                                         mediaSet.mHasVideos |= (sortCursor.getCurrentCursorIndex() == 1);
933                                 } while (sortCursor.moveToNext());
934                                 sortCursor.close();
935                         }
936                 } finally {
937                         if (sortCursor != null)
938                                 sortCursor.close();
939                 }
940
941                 sAlbumCache.put(ALBUM_CACHE_INCOMPLETE_INDEX, sDummyData);
942                 writeSetsToCache(sets);
943                 Log.i(TAG, "Done building albums.");
944                 // Now we must cache the items contained in every album / bucket.
945                 populateMediaItemsForSets(context, sets, acceleratedSets, false);
946                 sAlbumCache.delete(ALBUM_CACHE_INCOMPLETE_INDEX);
947                 Process.setThreadPriority(priority);
948
949                 // Complete any queued dirty requests
950                 processQueuedDirty(context);
951         }
952
953         private final static void refreshDirtySets(final Context context) {
954                 final byte[] existingData = sAlbumCache.get(ALBUM_CACHE_DIRTY_BUCKET_INDEX, 0);
955                 if (existingData != null && existingData.length > 0) {
956                         final long[] ids = toLongArray(existingData);
957                         final int numIds = ids.length;
958                         if (numIds > 0) {
959                                 final ArrayList<MediaSet> sets = new ArrayList<MediaSet>(numIds);
960                                 final LongSparseArray<MediaSet> acceleratedSets = new LongSparseArray<MediaSet>(numIds);
961                                 for (int i = 0; i < numIds; ++i) {
962                                         final MediaSet set = new MediaSet();
963                                         set.mId = ids[i];
964                                         sets.add(set);
965                                         acceleratedSets.put(set.mId, set);
966                                 }
967                                 Log.i(TAG, "Refreshing dirty albums");
968                                 populateMediaItemsForSets(context, sets, acceleratedSets, true);
969                         }
970                 }
971                 processQueuedDirty(context);
972                 sAlbumCache.delete(ALBUM_CACHE_DIRTY_BUCKET_INDEX);
973         }
974
975         private static final long[] computeDirtySets(final Context context) {
976                 final Uri uriImages = Images.Media.EXTERNAL_CONTENT_URI.buildUpon().appendQueryParameter("distinct", "true").build();
977                 final Uri uriVideos = Video.Media.EXTERNAL_CONTENT_URI.buildUpon().appendQueryParameter("distinct", "true").build();
978                 final ContentResolver cr = context.getContentResolver();
979
980                 final Cursor cursorImages = cr.query(uriImages, SENSE_PROJECTION, null, null, null);
981                 final Cursor cursorVideos = cr.query(uriVideos, SENSE_PROJECTION, null, null, null);
982                 Cursor[] cursors = new Cursor[2];
983                 cursors[0] = cursorImages;
984                 cursors[1] = cursorVideos;
985                 final MergeCursor cursor = new MergeCursor(cursors);
986                 long[] retVal = null;
987                 try {
988                         if (cursor.moveToFirst()) {
989                                 retVal = new long[cursor.getCount()];
990                                 int ctr = 0;
991                                 boolean allDirty = false;
992                                 do {
993                                         long setId = cursor.getLong(0);
994                                         retVal[ctr++] = setId;
995                                         byte[] data = sMetaAlbumCache.get(setId, 0);
996                                         if (data == null) {
997                                                 // We need to refresh everything.
998                                                 markDirty(context);
999                                                 allDirty = true;
1000                                         }
1001                                         if (!allDirty) {
1002                                                 long maxAdded = cursor.getLong(1);
1003                                                 long oldMaxAdded = toLong(data);
1004                                                 if (maxAdded > oldMaxAdded) {
1005                                                         markDirty(context, setId);
1006                                                 }
1007                                         }
1008                                 } while (cursor.moveToNext());
1009                         }
1010                 } finally {
1011                         cursor.close();
1012                 }
1013                 processQueuedDirty(context);
1014                 return retVal;
1015         }
1016
1017         private static final void processQueuedDirty(final Context context) {
1018                 if (QUEUE_DIRTY_SENSE) {
1019                         QUEUE_DIRTY_SENSE = false;
1020                         QUEUE_DIRTY_ALL = false;
1021                         QUEUE_DIRTY_SET = false;
1022                         computeDirtySets(context);
1023                 } else if (QUEUE_DIRTY_ALL) {
1024                         QUEUE_DIRTY_ALL = false;
1025                         QUEUE_DIRTY_SET = false;
1026                         QUEUE_DIRTY_SENSE = false;
1027                         refresh(context);
1028                 } else if (QUEUE_DIRTY_SET) {
1029                         QUEUE_DIRTY_SET = false;
1030                         // We don't mark QUEUE_DIRTY_SENSE because a set outside the dirty
1031                         // sets might have gotten modified.
1032                         refreshDirtySets(context);
1033                 }
1034         }
1035
1036         private final static void populateMediaItemsForSets(final Context context, final ArrayList<MediaSet> sets,
1037                 final LongSparseArray<MediaSet> acceleratedSets, boolean useWhere) {
1038                 if (sets == null || sets.size() == 0 || Thread.interrupted()) {
1039                         return;
1040                 }
1041                 Log.i(TAG, "Building items.");
1042                 final Uri uriImages = Images.Media.EXTERNAL_CONTENT_URI;
1043                 final Uri uriVideos = Video.Media.EXTERNAL_CONTENT_URI;
1044                 final ContentResolver cr = context.getContentResolver();
1045
1046                 String whereClause = null;
1047                 if (useWhere) {
1048                         int numSets = sets.size();
1049                         StringBuffer whereString = new StringBuffer(Images.ImageColumns.BUCKET_ID + " in (");
1050                         for (int i = 0; i < numSets; ++i) {
1051                                 whereString.append(sets.get(i).mId);
1052                                 if (i != numSets - 1) {
1053                                         whereString.append(",");
1054                                 }
1055                         }
1056                         whereString.append(")");
1057                         whereClause = whereString.toString();
1058                         Log.i(TAG, "Updating dirty albums where " + whereClause);
1059                 }
1060
1061                 final Cursor cursorImages = cr.query(uriImages, PROJECTION_IMAGES, whereClause, null, DEFAULT_IMAGE_SORT_ORDER);
1062                 final Cursor cursorVideos = cr.query(uriVideos, PROJECTION_VIDEOS, whereClause, null, DEFAULT_VIDEO_SORT_ORDER);
1063                 final Cursor[] cursors = new Cursor[2];
1064                 cursors[0] = cursorImages;
1065                 cursors[1] = cursorVideos;
1066                 final SortCursor sortCursor = new SortCursor(cursors, Images.ImageColumns.DATE_TAKEN, SortCursor.TYPE_NUMERIC, true);
1067                 if (Thread.interrupted()) {
1068                         return;
1069                 }
1070                 try {
1071                         if (sortCursor != null && sortCursor.moveToFirst()) {
1072                                 final int count = sortCursor.getCount();
1073                                 final int numSets = sets.size();
1074                                 final int approximateCountPerSet = count / numSets;
1075                                 for (int i = 0; i < numSets; ++i) {
1076                                         final MediaSet set = sets.get(i);
1077                                         set.getItems().clear();
1078                                         set.setNumExpectedItems(approximateCountPerSet);
1079                                 }
1080                                 do {
1081                                         if (Thread.interrupted()) {
1082                                                 return;
1083                                         }
1084                                         final MediaItem item = new MediaItem();
1085                                         final boolean isVideo = (sortCursor.getCurrentCursorIndex() == 1);
1086                                         if (isVideo) {
1087                                                 populateVideoItemFromCursor(item, cr, sortCursor, CacheService.BASE_CONTENT_STRING_VIDEOS);
1088                                         } else {
1089                                                 populateMediaItemFromCursor(item, cr, sortCursor, CacheService.BASE_CONTENT_STRING_IMAGES);
1090                                         }
1091                                         final long setId = sortCursor.getLong(MEDIA_BUCKET_ID_INDEX);
1092                                         final MediaSet set = findSet(setId, acceleratedSets);
1093                                         if (set != null) {
1094                                                 set.getItems().add(item);
1095                                         }
1096                                 } while (sortCursor.moveToNext());
1097                         }
1098                 } finally {
1099                         if (sortCursor != null)
1100                                 sortCursor.close();
1101                 }
1102                 if (sets.size() > 0) {
1103                         writeItemsToCache(sets);
1104                         Log.i(TAG, "Done building items.");
1105                 }
1106         }
1107
1108         private static final void writeSetsToCache(final ArrayList<MediaSet> sets) {
1109                 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
1110                 final int numSets = sets.size();
1111                 final DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(bos, 256));
1112                 try {
1113                         dos.writeInt(numSets);
1114                         for (int i = 0; i < numSets; ++i) {
1115                                 if (Thread.interrupted()) {
1116                                         return;
1117                                 }
1118                                 final MediaSet set = sets.get(i);
1119                                 dos.writeLong(set.mId);
1120                                 Utils.writeUTF(dos, set.mName);
1121                                 dos.writeBoolean(set.mHasImages);
1122                                 dos.writeBoolean(set.mHasVideos);
1123                         }
1124                         dos.flush();
1125                         sAlbumCache.put(ALBUM_CACHE_METADATA_INDEX, bos.toByteArray());
1126                         dos.close();
1127                         if (numSets == 0) {
1128                                 sAlbumCache.deleteAll();
1129                                 putLocaleForAlbumCache(Locale.getDefault());
1130                         }
1131                         sAlbumCache.flush();
1132                 } catch (IOException e) {
1133                         Log.e(TAG, "Error writing albums to diskcache.");
1134                         sAlbumCache.deleteAll();
1135                         putLocaleForAlbumCache(Locale.getDefault());
1136                 }
1137         }
1138
1139         private static final void writeItemsToCache(final ArrayList<MediaSet> sets) {
1140                 final int numSets = sets.size();
1141                 for (int i = 0; i < numSets; ++i) {
1142                         if (Thread.interrupted()) {
1143                                 return;
1144                         }
1145                         writeItemsForASet(sets.get(i));
1146                 }
1147                 writeMetaAlbumCache(sets);
1148                 sAlbumCache.flush();
1149         }
1150
1151         private static final void writeMetaAlbumCache(ArrayList<MediaSet> sets) {
1152                 final int numSets = sets.size();
1153                 for (int i = 0; i < numSets; ++i) {
1154                         final MediaSet set = sets.get(i);
1155                         byte[] data = longToByteArray(set.mMaxAddedTimestamp);
1156                         sMetaAlbumCache.put(set.mId, data);
1157                 }
1158                 sMetaAlbumCache.flush();
1159         }
1160
1161         private static final void writeItemsForASet(final MediaSet set) {
1162                 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
1163                 final DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(bos, 256));
1164                 try {
1165                         final ArrayList<MediaItem> items = set.getItems();
1166                         final int numItems = items.size();
1167                         dos.writeInt(numItems);
1168                         dos.writeLong(set.mMinTimestamp);
1169                         dos.writeLong(set.mMaxTimestamp);
1170                         for (int i = 0; i < numItems; ++i) {
1171                                 MediaItem item = items.get(i);
1172                                 if (set.mId == LocalDataSource.CAMERA_BUCKET_ID || set.mId == LocalDataSource.DOWNLOAD_BUCKET_ID) {
1173                                         // Reverse the display order for the camera bucket - want
1174                                         // the latest first.
1175                                         item = items.get(numItems - i - 1);
1176                                 }
1177                                 dos.writeLong(item.mId);
1178                                 Utils.writeUTF(dos, item.mCaption);
1179                                 Utils.writeUTF(dos, item.mMimeType);
1180                                 dos.writeInt(item.getMediaType());
1181                                 dos.writeDouble(item.mLatitude);
1182                                 dos.writeDouble(item.mLongitude);
1183                                 dos.writeLong(item.mDateTakenInMs);
1184                                 dos.writeBoolean(item.mTriedRetrievingExifDateTaken);
1185                                 dos.writeLong(item.mDateAddedInSec);
1186                                 dos.writeLong(item.mDateModifiedInSec);
1187                                 dos.writeInt(item.mDurationInSec);
1188                                 dos.writeInt((int) item.mRotation);
1189                                 Utils.writeUTF(dos, item.mFilePath);
1190                         }
1191                         dos.flush();
1192                         sAlbumCache.put(set.mId, bos.toByteArray());
1193                         dos.close();
1194                 } catch (IOException e) {
1195                         Log.e(TAG, "Error writing to diskcache for set " + set.mName);
1196                         sAlbumCache.deleteAll();
1197                         putLocaleForAlbumCache(Locale.getDefault());
1198                 }
1199         }
1200
1201         private static final MediaSet findSet(final long id, final LongSparseArray<MediaSet> acceleratedTable) {
1202                 // This is the accelerated lookup table for the MediaSet based on set
1203                 // id.
1204                 return acceleratedTable.get(id);
1205         }
1206 }