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