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