LocalAlbumSet.java revision 84c220f10a643927c8a2126de8a755d8d7f7ec9e
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.gallery3d.data; 18 19import android.content.ContentResolver; 20import android.database.Cursor; 21import android.net.Uri; 22import android.provider.MediaStore.Files; 23import android.provider.MediaStore.Files.FileColumns; 24import android.provider.MediaStore.Images; 25import android.provider.MediaStore.Images.ImageColumns; 26import android.provider.MediaStore.Video; 27 28import com.android.gallery3d.R; 29import com.android.gallery3d.app.GalleryApp; 30import com.android.gallery3d.common.Utils; 31import com.android.gallery3d.util.GalleryUtils; 32import com.android.gallery3d.util.MediaSetUtils; 33 34import java.util.ArrayList; 35import java.util.Comparator; 36 37// LocalAlbumSet lists all image or video albums in the local storage. 38// The path should be "/local/image", "local/video" or "/local/all" 39public class LocalAlbumSet extends MediaSet { 40 public static final Path PATH_ALL = Path.fromString("/local/all"); 41 public static final Path PATH_IMAGE = Path.fromString("/local/image"); 42 public static final Path PATH_VIDEO = Path.fromString("/local/video"); 43 44 private static final String TAG = "LocalAlbumSet"; 45 private static final String EXTERNAL_MEDIA = "external"; 46 47 // The indices should match the following projections. 48 private static final int INDEX_BUCKET_ID = 0; 49 private static final int INDEX_MEDIA_TYPE = 1; 50 private static final int INDEX_BUCKET_NAME = 2; 51 52 private static final Uri mBaseUri = Files.getContentUri(EXTERNAL_MEDIA); 53 private static final Uri mWatchUriImage = Images.Media.EXTERNAL_CONTENT_URI; 54 private static final Uri mWatchUriVideo = Video.Media.EXTERNAL_CONTENT_URI; 55 56 // BUCKET_DISPLAY_NAME is a string like "Camera" which is the directory 57 // name of where an image or video is in. BUCKET_ID is a hash of the path 58 // name of that directory (see computeBucketValues() in MediaProvider for 59 // details). MEDIA_TYPE is video, image, audio, etc. 60 // 61 // The "albums" are not explicitly recorded in the database, but each image 62 // or video has the two columns (BUCKET_ID, MEDIA_TYPE). We define an 63 // "album" to be the collection of images/videos which have the same value 64 // for the two columns. 65 // 66 // The goal of the query (used in loadSubMediaSets()) is to find all albums, 67 // that is, all unique values for (BUCKET_ID, MEDIA_TYPE). In the meantime 68 // sort them by the timestamp of the latest image/video in each of the album. 69 // 70 // The order of columns below is important: it must match to the index in 71 // MediaStore. 72 private static final String[] PROJECTION_BUCKET = { 73 ImageColumns.BUCKET_ID, 74 FileColumns.MEDIA_TYPE, 75 ImageColumns.BUCKET_DISPLAY_NAME }; 76 77 // We want to order the albums by reverse chronological order. We abuse the 78 // "WHERE" parameter to insert a "GROUP BY" clause into the SQL statement. 79 // The template for "WHERE" parameter is like: 80 // SELECT ... FROM ... WHERE (%s) 81 // and we make it look like: 82 // SELECT ... FROM ... WHERE (1) GROUP BY 1,(2) 83 // The "(1)" means true. The "1,(2)" means the first two columns specified 84 // after SELECT. Note that because there is a ")" in the template, we use 85 // "(2" to match it. 86 private static final String BUCKET_GROUP_BY = 87 "1) GROUP BY 1,(2"; 88 private static final String BUCKET_ORDER_BY = "MAX(datetaken) DESC"; 89 90 private final GalleryApp mApplication; 91 private final int mType; 92 private ArrayList<MediaSet> mAlbums = new ArrayList<MediaSet>(); 93 private final ChangeNotifier mNotifierImage; 94 private final ChangeNotifier mNotifierVideo; 95 private final String mName; 96 97 public LocalAlbumSet(Path path, GalleryApp application) { 98 super(path, nextVersionNumber()); 99 mApplication = application; 100 mType = getTypeFromPath(path); 101 mNotifierImage = new ChangeNotifier(this, mWatchUriImage, application); 102 mNotifierVideo = new ChangeNotifier(this, mWatchUriVideo, application); 103 mName = application.getResources().getString( 104 R.string.set_label_local_albums); 105 } 106 107 private static int getTypeFromPath(Path path) { 108 String name[] = path.split(); 109 if (name.length < 2) { 110 throw new IllegalArgumentException(path.toString()); 111 } 112 if ("all".equals(name[1])) return MEDIA_TYPE_ALL; 113 if ("image".equals(name[1])) return MEDIA_TYPE_IMAGE; 114 if ("video".equals(name[1])) return MEDIA_TYPE_VIDEO; 115 throw new IllegalArgumentException(path.toString()); 116 } 117 118 @Override 119 public MediaSet getSubMediaSet(int index) { 120 return mAlbums.get(index); 121 } 122 123 @Override 124 public int getSubMediaSetCount() { 125 return mAlbums.size(); 126 } 127 128 @Override 129 public String getName() { 130 return mName; 131 } 132 133 private BucketEntry[] loadBucketEntries(Cursor cursor) { 134 ArrayList<BucketEntry> buffer = new ArrayList<BucketEntry>(); 135 int typeBits = 0; 136 if ((mType & MEDIA_TYPE_IMAGE) != 0) { 137 typeBits |= (1 << FileColumns.MEDIA_TYPE_IMAGE); 138 } 139 if ((mType & MEDIA_TYPE_VIDEO) != 0) { 140 typeBits |= (1 << FileColumns.MEDIA_TYPE_VIDEO); 141 } 142 try { 143 while (cursor.moveToNext()) { 144 if ((typeBits & (1 << cursor.getInt(INDEX_MEDIA_TYPE))) != 0) { 145 BucketEntry entry = new BucketEntry( 146 cursor.getInt(INDEX_BUCKET_ID), 147 cursor.getString(INDEX_BUCKET_NAME)); 148 if (!buffer.contains(entry)) { 149 buffer.add(entry); 150 } 151 } 152 } 153 } finally { 154 cursor.close(); 155 } 156 return buffer.toArray(new BucketEntry[buffer.size()]); 157 } 158 159 160 private static int findBucket(BucketEntry entries[], int bucketId) { 161 for (int i = 0, n = entries.length; i < n ; ++i) { 162 if (entries[i].bucketId == bucketId) return i; 163 } 164 return -1; 165 } 166 167 @SuppressWarnings("unchecked") 168 protected ArrayList<MediaSet> loadSubMediaSets() { 169 // Note: it will be faster if we only select media_type and bucket_id. 170 // need to test the performance if that is worth 171 172 Uri uri = mBaseUri; 173 GalleryUtils.assertNotInRenderThread(); 174 Cursor cursor = mApplication.getContentResolver().query( 175 uri, PROJECTION_BUCKET, BUCKET_GROUP_BY, null, BUCKET_ORDER_BY); 176 if (cursor == null) { 177 Log.w(TAG, "cannot open local database: " + uri); 178 return new ArrayList<MediaSet>(); 179 } 180 BucketEntry[] entries = loadBucketEntries(cursor); 181 int offset = 0; 182 183 // Move camera and download bucket to the front, while keeping the 184 // order of others. 185 int index = findBucket(entries, MediaSetUtils.CAMERA_BUCKET_ID); 186 if (index != -1) { 187 circularShiftRight(entries, offset++, index); 188 } 189 index = findBucket(entries, MediaSetUtils.DOWNLOAD_BUCKET_ID); 190 if (index != -1) { 191 circularShiftRight(entries, offset++, index); 192 } 193 194 ArrayList<MediaSet> albums = new ArrayList<MediaSet>(); 195 DataManager dataManager = mApplication.getDataManager(); 196 for (BucketEntry entry : entries) { 197 albums.add(getLocalAlbum(dataManager, 198 mType, mPath, entry.bucketId, entry.bucketName)); 199 } 200 for (int i = 0, n = albums.size(); i < n; ++i) { 201 albums.get(i).reload(); 202 } 203 return albums; 204 } 205 206 private MediaSet getLocalAlbum( 207 DataManager manager, int type, Path parent, int id, String name) { 208 Path path = parent.getChild(id); 209 MediaObject object = manager.peekMediaObject(path); 210 if (object != null) return (MediaSet) object; 211 switch (type) { 212 case MEDIA_TYPE_IMAGE: 213 return new LocalAlbum(path, mApplication, id, true, name); 214 case MEDIA_TYPE_VIDEO: 215 return new LocalAlbum(path, mApplication, id, false, name); 216 case MEDIA_TYPE_ALL: 217 Comparator<MediaItem> comp = DataManager.sDateTakenComparator; 218 return new LocalMergeAlbum(path, comp, new MediaSet[] { 219 getLocalAlbum(manager, MEDIA_TYPE_IMAGE, PATH_IMAGE, id, name), 220 getLocalAlbum(manager, MEDIA_TYPE_VIDEO, PATH_VIDEO, id, name)}, id); 221 } 222 throw new IllegalArgumentException(String.valueOf(type)); 223 } 224 225 public static String getBucketName(ContentResolver resolver, int bucketId) { 226 Uri uri = mBaseUri.buildUpon() 227 .appendQueryParameter("limit", "1") 228 .build(); 229 230 Cursor cursor = resolver.query( 231 uri, PROJECTION_BUCKET, "bucket_id = ?", 232 new String[]{String.valueOf(bucketId)}, null); 233 234 if (cursor == null) { 235 Log.w(TAG, "query fail: " + uri); 236 return ""; 237 } 238 try { 239 return cursor.moveToNext() 240 ? cursor.getString(INDEX_BUCKET_NAME) 241 : ""; 242 } finally { 243 cursor.close(); 244 } 245 } 246 247 @Override 248 public long reload() { 249 // "|" is used instead of "||" because we want to clear both flags. 250 if (mNotifierImage.isDirty() | mNotifierVideo.isDirty()) { 251 mDataVersion = nextVersionNumber(); 252 mAlbums = loadSubMediaSets(); 253 } 254 return mDataVersion; 255 } 256 257 // For debug only. Fake there is a ContentObserver.onChange() event. 258 void fakeChange() { 259 mNotifierImage.fakeChange(); 260 mNotifierVideo.fakeChange(); 261 } 262 263 private static class BucketEntry { 264 public String bucketName; 265 public int bucketId; 266 267 public BucketEntry(int id, String name) { 268 bucketId = id; 269 bucketName = Utils.ensureNotNull(name); 270 } 271 272 @Override 273 public int hashCode() { 274 return bucketId; 275 } 276 277 @Override 278 public boolean equals(Object object) { 279 if (!(object instanceof BucketEntry)) return false; 280 BucketEntry entry = (BucketEntry) object; 281 return bucketId == entry.bucketId; 282 } 283 } 284 285 // Circular shift the array range from a[i] to a[j] (inclusive). That is, 286 // a[i] -> a[i+1] -> a[i+2] -> ... -> a[j], and a[j] -> a[i] 287 private static <T> void circularShiftRight(T[] array, int i, int j) { 288 T temp = array[j]; 289 for (int k = j; k > i; k--) { 290 array[k] = array[k - 1]; 291 } 292 array[i] = temp; 293 } 294} 295