LocalAlbumSet.java revision d134e18e3c2d9614099d3b74e1a6a12159a1e81a
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;
27import android.util.Log;
28
29import com.android.gallery3d.R;
30import com.android.gallery3d.app.GalleryApp;
31import com.android.gallery3d.common.Utils;
32import com.android.gallery3d.util.Future;
33import com.android.gallery3d.util.FutureListener;
34import com.android.gallery3d.util.MediaSetUtils;
35import com.android.gallery3d.util.ThreadPool;
36import com.android.gallery3d.util.ThreadPool.JobContext;
37
38import java.util.ArrayList;
39import java.util.Comparator;
40
41// LocalAlbumSet lists all image or video albums in the local storage.
42// The path should be "/local/image", "local/video" or "/local/all"
43public class LocalAlbumSet extends MediaSet
44        implements FutureListener<ArrayList<MediaSet>> {
45    public static final Path PATH_ALL = Path.fromString("/local/all");
46    public static final Path PATH_IMAGE = Path.fromString("/local/image");
47    public static final Path PATH_VIDEO = Path.fromString("/local/video");
48
49    private static final String TAG = "LocalAlbumSet";
50    private static final String EXTERNAL_MEDIA = "external";
51
52    // The indices should match the following projections.
53    private static final int INDEX_BUCKET_ID = 0;
54    private static final int INDEX_MEDIA_TYPE = 1;
55    private static final int INDEX_BUCKET_NAME = 2;
56
57    private static final Uri mBaseUri = Files.getContentUri(EXTERNAL_MEDIA);
58    private static final Uri mWatchUriImage = Images.Media.EXTERNAL_CONTENT_URI;
59    private static final Uri mWatchUriVideo = Video.Media.EXTERNAL_CONTENT_URI;
60
61    // BUCKET_DISPLAY_NAME is a string like "Camera" which is the directory
62    // name of where an image or video is in. BUCKET_ID is a hash of the path
63    // name of that directory (see computeBucketValues() in MediaProvider for
64    // details). MEDIA_TYPE is video, image, audio, etc.
65    //
66    // The "albums" are not explicitly recorded in the database, but each image
67    // or video has the two columns (BUCKET_ID, MEDIA_TYPE). We define an
68    // "album" to be the collection of images/videos which have the same value
69    // for the two columns.
70    //
71    // The goal of the query (used in loadSubMediaSets()) is to find all albums,
72    // that is, all unique values for (BUCKET_ID, MEDIA_TYPE). In the meantime
73    // sort them by the timestamp of the latest image/video in each of the album.
74    //
75    // The order of columns below is important: it must match to the index in
76    // MediaStore.
77    private static final String[] PROJECTION_BUCKET = {
78            ImageColumns.BUCKET_ID,
79            FileColumns.MEDIA_TYPE,
80            ImageColumns.BUCKET_DISPLAY_NAME };
81
82    // We want to order the albums by reverse chronological order. We abuse the
83    // "WHERE" parameter to insert a "GROUP BY" clause into the SQL statement.
84    // The template for "WHERE" parameter is like:
85    //    SELECT ... FROM ... WHERE (%s)
86    // and we make it look like:
87    //    SELECT ... FROM ... WHERE (1) GROUP BY 1,(2)
88    // The "(1)" means true. The "1,(2)" means the first two columns specified
89    // after SELECT. Note that because there is a ")" in the template, we use
90    // "(2" to match it.
91    private static final String BUCKET_GROUP_BY =
92            "1) GROUP BY 1,(2";
93    private static final String BUCKET_ORDER_BY = "MAX(datetaken) DESC";
94
95    private final GalleryApp mApplication;
96    private final int mType;
97    private ArrayList<MediaSet> mAlbums = new ArrayList<MediaSet>();
98    private final ChangeNotifier mNotifierImage;
99    private final ChangeNotifier mNotifierVideo;
100    private final String mName;
101    private Future<ArrayList<MediaSet>> mLoadTask;
102    private ArrayList<MediaSet> mLoadBuffer;
103
104    public LocalAlbumSet(Path path, GalleryApp application) {
105        super(path, nextVersionNumber());
106        mApplication = application;
107        mType = getTypeFromPath(path);
108        mNotifierImage = new ChangeNotifier(this, mWatchUriImage, application);
109        mNotifierVideo = new ChangeNotifier(this, mWatchUriVideo, application);
110        mName = application.getResources().getString(
111                R.string.set_label_local_albums);
112    }
113
114    private static int getTypeFromPath(Path path) {
115        String name[] = path.split();
116        if (name.length < 2) {
117            throw new IllegalArgumentException(path.toString());
118        }
119        return getTypeFromString(name[1]);
120    }
121
122    @Override
123    public MediaSet getSubMediaSet(int index) {
124        return mAlbums.get(index);
125    }
126
127    @Override
128    public int getSubMediaSetCount() {
129        return mAlbums.size();
130    }
131
132    @Override
133    public String getName() {
134        return mName;
135    }
136
137    private BucketEntry[] loadBucketEntries(JobContext jc) {
138        Uri uri = mBaseUri;
139
140        Log.v("DebugLoadingTime", "start quering media provider");
141        Cursor cursor = mApplication.getContentResolver().query(
142                uri, PROJECTION_BUCKET, BUCKET_GROUP_BY, null, BUCKET_ORDER_BY);
143        if (cursor == null) {
144            Log.w(TAG, "cannot open local database: " + uri);
145            return new BucketEntry[0];
146        }
147        ArrayList<BucketEntry> buffer = new ArrayList<BucketEntry>();
148        int typeBits = 0;
149        if ((mType & MEDIA_TYPE_IMAGE) != 0) {
150            typeBits |= (1 << FileColumns.MEDIA_TYPE_IMAGE);
151        }
152        if ((mType & MEDIA_TYPE_VIDEO) != 0) {
153            typeBits |= (1 << FileColumns.MEDIA_TYPE_VIDEO);
154        }
155        try {
156            while (cursor.moveToNext()) {
157                if ((typeBits & (1 << cursor.getInt(INDEX_MEDIA_TYPE))) != 0) {
158                    BucketEntry entry = new BucketEntry(
159                            cursor.getInt(INDEX_BUCKET_ID),
160                            cursor.getString(INDEX_BUCKET_NAME));
161                    if (!buffer.contains(entry)) {
162                        buffer.add(entry);
163                    }
164                }
165                if (jc.isCancelled()) return null;
166            }
167            Log.v("DebugLoadingTime", "got " + buffer.size() + " buckets");
168        } finally {
169            cursor.close();
170        }
171        return buffer.toArray(new BucketEntry[buffer.size()]);
172    }
173
174
175    private static int findBucket(BucketEntry entries[], int bucketId) {
176        for (int i = 0, n = entries.length; i < n ; ++i) {
177            if (entries[i].bucketId == bucketId) return i;
178        }
179        return -1;
180    }
181
182    private class AlbumsLoader implements ThreadPool.Job<ArrayList<MediaSet>> {
183
184        @Override
185        @SuppressWarnings("unchecked")
186        public ArrayList<MediaSet> run(JobContext jc) {
187            // Note: it will be faster if we only select media_type and bucket_id.
188            //       need to test the performance if that is worth
189            BucketEntry[] entries = loadBucketEntries(jc);
190
191            if (jc.isCancelled()) return null;
192
193            int offset = 0;
194            // Move camera and download bucket to the front, while keeping the
195            // order of others.
196            int index = findBucket(entries, MediaSetUtils.CAMERA_BUCKET_ID);
197            if (index != -1) {
198                circularShiftRight(entries, offset++, index);
199            }
200            index = findBucket(entries, MediaSetUtils.DOWNLOAD_BUCKET_ID);
201            if (index != -1) {
202                circularShiftRight(entries, offset++, index);
203            }
204
205            ArrayList<MediaSet> albums = new ArrayList<MediaSet>();
206            DataManager dataManager = mApplication.getDataManager();
207            for (BucketEntry entry : entries) {
208                MediaSet album = getLocalAlbum(dataManager,
209                        mType, mPath, entry.bucketId, entry.bucketName);
210                album.reload();
211                albums.add(album);
212            }
213            return albums;
214        }
215    }
216
217    private MediaSet getLocalAlbum(
218            DataManager manager, int type, Path parent, int id, String name) {
219        synchronized (DataManager.LOCK) {
220            Path path = parent.getChild(id);
221            MediaObject object = manager.peekMediaObject(path);
222            if (object != null) return (MediaSet) object;
223            switch (type) {
224                case MEDIA_TYPE_IMAGE:
225                    return new LocalAlbum(path, mApplication, id, true, name);
226                case MEDIA_TYPE_VIDEO:
227                    return new LocalAlbum(path, mApplication, id, false, name);
228                case MEDIA_TYPE_ALL:
229                    Comparator<MediaItem> comp = DataManager.sDateTakenComparator;
230                    return new LocalMergeAlbum(path, comp, new MediaSet[] {
231                            getLocalAlbum(manager, MEDIA_TYPE_IMAGE, PATH_IMAGE, id, name),
232                            getLocalAlbum(manager, MEDIA_TYPE_VIDEO, PATH_VIDEO, id, name)}, id);
233            }
234            throw new IllegalArgumentException(String.valueOf(type));
235        }
236    }
237
238    public static String getBucketName(ContentResolver resolver, int bucketId) {
239        Uri uri = mBaseUri.buildUpon()
240                .appendQueryParameter("limit", "1")
241                .build();
242
243        Cursor cursor = resolver.query(
244                uri, PROJECTION_BUCKET, "bucket_id = ?",
245                new String[]{String.valueOf(bucketId)}, null);
246
247        if (cursor == null) {
248            Log.w(TAG, "query fail: " + uri);
249            return "";
250        }
251        try {
252            return cursor.moveToNext()
253                    ? cursor.getString(INDEX_BUCKET_NAME)
254                    : "";
255        } finally {
256            cursor.close();
257        }
258    }
259
260    @Override
261    // synchronized on this function for
262    //   1. Prevent calling reload() concurrently.
263    //   2. Prevent calling onFutureDone() and reload() concurrently
264    public synchronized long reload() {
265        // "|" is used instead of "||" because we want to clear both flags.
266        if (mNotifierImage.isDirty() | mNotifierVideo.isDirty()) {
267            if (mLoadTask != null) mLoadTask.cancel();
268            mLoadTask = mApplication.getThreadPool().submit(new AlbumsLoader(), this);
269        }
270        if (mLoadBuffer != null) {
271            mAlbums = mLoadBuffer;
272            mLoadBuffer = null;
273            mDataVersion = nextVersionNumber();
274        }
275        return mDataVersion;
276    }
277
278    @Override
279    public synchronized void onFutureDone(Future<ArrayList<MediaSet>> future) {
280        if (mLoadTask != future) return; // ignore, wait for the latest task
281        mLoadBuffer = future.get();
282        if (mLoadBuffer == null) mLoadBuffer = new ArrayList<MediaSet>();
283        notifyContentChanged();
284    }
285
286    // For debug only. Fake there is a ContentObserver.onChange() event.
287    void fakeChange() {
288        mNotifierImage.fakeChange();
289        mNotifierVideo.fakeChange();
290    }
291
292    private static class BucketEntry {
293        public String bucketName;
294        public int bucketId;
295
296        public BucketEntry(int id, String name) {
297            bucketId = id;
298            bucketName = Utils.ensureNotNull(name);
299        }
300
301        @Override
302        public int hashCode() {
303            return bucketId;
304        }
305
306        @Override
307        public boolean equals(Object object) {
308            if (!(object instanceof BucketEntry)) return false;
309            BucketEntry entry = (BucketEntry) object;
310            return bucketId == entry.bucketId;
311        }
312    }
313
314    // Circular shift the array range from a[i] to a[j] (inclusive). That is,
315    // a[i] -> a[i+1] -> a[i+2] -> ... -> a[j], and a[j] -> a[i]
316    private static <T> void circularShiftRight(T[] array, int i, int j) {
317        T temp = array[j];
318        for (int k = j; k > i; k--) {
319            array[k] = array[k - 1];
320        }
321        array[i] = temp;
322    }
323}
324