OSDN Git Service

Picking up dirty albums when something is deleted
[android-x86/packages-apps-Gallery2.git] / src / com / cooliris / media / LocalDataSource.java
1 package com.cooliris.media;
2
3 import java.io.File;
4 import java.net.URI;
5 import java.util.ArrayList;
6
7 import android.content.ContentResolver;
8 import android.content.ContentUris;
9 import android.content.ContentValues;
10 import android.content.Context;
11 import android.database.ContentObserver;
12 import android.database.Cursor;
13 import android.media.ExifInterface;
14 import android.net.Uri;
15 import android.os.Environment;
16 import android.os.Handler;
17 import android.provider.MediaStore.Images;
18 import android.provider.MediaStore.Video;
19 import android.util.Log;
20
21 import com.cooliris.cache.CacheService;
22
23 public final class LocalDataSource implements DataSource {
24     private static final String TAG = "LocalDataSource";
25
26     public static final DiskCache sThumbnailCache = new DiskCache("local-image-thumbs");
27     public static final DiskCache sThumbnailCacheVideo = new DiskCache("local-video-thumbs");
28
29     public static final String CAMERA_STRING = "Camera";
30     public static final String DOWNLOAD_STRING = "download";
31     public static final String CAMERA_BUCKET_NAME = Environment.getExternalStorageDirectory().toString() + "/DCIM/" + CAMERA_STRING;
32     public static final String DOWNLOAD_BUCKET_NAME = Environment.getExternalStorageDirectory().toString() + "/" + DOWNLOAD_STRING;
33     public static final int CAMERA_BUCKET_ID = getBucketId(CAMERA_BUCKET_NAME);
34     public static final int DOWNLOAD_BUCKET_ID = getBucketId(DOWNLOAD_BUCKET_NAME);
35
36     public static boolean sObserverActive = false;
37     private boolean mDisableImages;
38     private boolean mDisableVideos;
39
40     /**
41      * Matches code in MediaProvider.computeBucketValues. Should be a common
42      * function.
43      */
44     public static int getBucketId(String path) {
45         return (path.toLowerCase().hashCode());
46     }
47
48     private Context mContext;
49     private ContentObserver mObserver;
50
51     public LocalDataSource(Context context) {
52         mContext = context;
53     }
54
55     public void setMimeFilter(boolean disableImages, boolean disableVideos) {
56         mDisableImages = disableImages;
57         mDisableVideos = disableVideos;
58     }
59
60     public void loadMediaSets(final MediaFeed feed) {
61         if (mContext == null) {
62             return;
63         }
64         stopListeners();
65         CacheService.loadMediaSets(feed, this, !mDisableImages, !mDisableVideos);
66         Handler handler = ((Gallery) mContext).getHandler();
67         ContentObserver observer = new ContentObserver(handler) {
68             public void onChange(boolean selfChange) {
69                 final boolean isPaused = ((Gallery) mContext).isPaused();
70                 if (isPaused) {
71                     MediaSet mediaSet = feed.getCurrentSet();
72                     if (mediaSet != null) {
73                         CacheService.markDirtyImmediate(mediaSet.mId);
74                         refreshUI(feed, mediaSet.mId);
75                     }
76                 }
77                 CacheService.senseDirty(mContext, new CacheService.Observer() {
78                     public void onChange(long[] ids) {
79                         if (!isPaused)
80                             return;
81                         if (ids != null) {
82                             int numLongs = ids.length;
83                             for (int i = 0; i < numLongs; ++i) {
84                                 refreshUI(feed, ids[i]);
85                             }
86                         }
87                     }
88                 });
89             }
90         };
91
92         // Start listening.
93         Uri uriImages = Images.Media.EXTERNAL_CONTENT_URI;
94         Uri uriVideos = Video.Media.EXTERNAL_CONTENT_URI;
95         ContentResolver cr = mContext.getContentResolver();
96         mObserver = observer;
97         cr.registerContentObserver(uriImages, true, observer);
98         cr.registerContentObserver(uriVideos, true, observer);
99         sObserverActive = true;
100     }
101
102     public void shutdown() {
103         stopListeners();
104     }
105
106     private void stopListeners() {
107         ContentResolver cr = mContext.getContentResolver();
108         if (mObserver != null) {
109             cr.unregisterContentObserver(mObserver);
110         }
111         sObserverActive = false;
112     }
113
114     protected void refreshUI(MediaFeed feed, long setIdToUse) {
115         if (setIdToUse == Shared.INVALID) {
116             return;
117         }
118         if (feed.getMediaSet(setIdToUse) == null) {
119             MediaSet mediaSet = feed.addMediaSet(setIdToUse, this);
120             if (setIdToUse == CAMERA_BUCKET_ID) {
121                 mediaSet.mName = CAMERA_STRING;
122             } else if (setIdToUse == DOWNLOAD_BUCKET_ID) {
123                 mediaSet.mName = DOWNLOAD_STRING;
124             }
125             mediaSet.generateTitle(true);
126         } else {
127             MediaSet mediaSet = feed.replaceMediaSet(setIdToUse, this);
128             Log.i(TAG, "Replacing mediaset " + mediaSet.mName + " id " + setIdToUse + " current Id " + mediaSet.mId);
129             if (setIdToUse == CAMERA_BUCKET_ID) {
130                 mediaSet.mName = CAMERA_STRING;
131             } else if (setIdToUse == DOWNLOAD_BUCKET_ID) {
132                 mediaSet.mName = DOWNLOAD_STRING;
133             }
134             mediaSet.generateTitle(true);
135         }
136     }
137
138     public void loadItemsForSet(final MediaFeed feed, final MediaSet parentSet, int rangeStart, int rangeEnd) {
139         // Quick load from the cache.
140         if (mContext == null || parentSet == null) {
141             return;
142         }
143         loadMediaItemsIntoMediaFeed(feed, parentSet, rangeStart, rangeEnd);
144     }
145
146     private void loadMediaItemsIntoMediaFeed(final MediaFeed mediaFeed, final MediaSet set, int rangeStart, int rangeEnd) {
147         if (rangeEnd - rangeStart < 0) {
148             return;
149         }
150         CacheService.loadMediaItemsIntoMediaFeed(mediaFeed, set, rangeStart, rangeEnd, !mDisableImages, !mDisableVideos);
151         if (set.mId == CAMERA_BUCKET_ID) {
152             mediaFeed.moveSetToFront(set);
153         }
154     }
155
156     public boolean performOperation(final int operation, final ArrayList<MediaBucket> mediaBuckets, final Object data) {
157         int numBuckets = mediaBuckets.size();
158         ContentResolver cr = mContext.getContentResolver();
159         switch (operation) {
160         case MediaFeed.OPERATION_DELETE:
161             for (int i = 0; i < numBuckets; ++i) {
162                 MediaBucket bucket = mediaBuckets.get(i);
163                 MediaSet set = bucket.mediaSet;
164                 ArrayList<MediaItem> items = bucket.mediaItems;
165                 if (set != null && items == null) {
166                     // Remove the entire bucket.
167                     final Uri uriImages = Images.Media.EXTERNAL_CONTENT_URI;
168                     final Uri uriVideos = Video.Media.EXTERNAL_CONTENT_URI;
169                     final String whereImages = Images.ImageColumns.BUCKET_ID + "=" + Long.toString(set.mId);
170                     final String whereVideos = Video.VideoColumns.BUCKET_ID + "=" + Long.toString(set.mId);
171                     cr.delete(uriImages, whereImages, null);
172                     cr.delete(uriVideos, whereVideos, null);
173                     CacheService.markDirty(mContext);
174                 }
175                 if (set != null && items != null) {
176                     // We need to remove these items from the set.
177                     int numItems = items.size();
178                     try {
179                         for (int j = 0; j < numItems; ++j) {
180                             MediaItem item = items.get(j);
181                             cr.delete(Uri.parse(item.mContentUri), null, null);
182                         }
183                     } catch (Exception e) {
184                         // If the database operation failed for any reason.
185                         ;
186                     }
187                     set.updateNumExpectedItems();
188                     set.generateTitle(true);
189                     CacheService.markDirty(mContext, set.mId);
190                 }
191             }
192             break;
193         case MediaFeed.OPERATION_ROTATE:
194             for (int i = 0; i < numBuckets; ++i) {
195                 MediaBucket bucket = mediaBuckets.get(i);
196                 ArrayList<MediaItem> items = bucket.mediaItems;
197                 if (items == null) {
198                     continue;
199                 }
200                 float angleToRotate = ((Float) data).floatValue();
201                 if (angleToRotate == 0) {
202                     return true;
203                 }
204                 int numItems = items.size();
205                 for (int j = 0; j < numItems; ++j) {
206                     rotateItem(items.get(j), angleToRotate);
207                 }
208             }
209             break;
210         }
211         return true;
212     }
213
214     private void rotateItem(final MediaItem item, float angleToRotate) {
215         ContentResolver cr = mContext.getContentResolver();
216         try {
217             int currentOrientation = (int) item.mRotation;
218             angleToRotate += currentOrientation;
219             float rotation = Shared.normalizePositive(angleToRotate);
220             String rotationString = Integer.toString((int) rotation);
221
222             // Update the database entry.
223             ContentValues values = new ContentValues();
224             values.put(Images.ImageColumns.ORIENTATION, rotationString);
225             try {
226                 cr.update(Uri.parse(item.mContentUri), values, null, null);
227             } catch (Exception e) {
228                 // If the database operation fails for any reason.
229                 ;
230             }
231
232             // Update the file EXIF information.
233             Uri uri = Uri.parse(item.mContentUri);
234             String uriScheme = uri.getScheme();
235             if (uriScheme.equals("file")) {
236                 ExifInterface exif = new ExifInterface(uri.getPath());
237                 exif.setAttribute(ExifInterface.TAG_ORIENTATION, Integer.toString(Shared.degreesToExifOrientation(rotation)));
238                 exif.saveAttributes();
239             }
240
241             // Invalidate the cache entry.
242             CacheService.markDirty(mContext, item.mParentMediaSet.mId);
243
244             // Update the object representation of the item.
245             item.mRotation = rotation;
246         } catch (Exception e) {
247             // System.out.println("Apparently not a JPEG");
248         }
249     }
250
251     public DiskCache getThumbnailCache() {
252         return sThumbnailCache;
253     }
254
255     public static MediaItem createMediaItemFromUri(Context context, Uri target) {
256         MediaItem item = null;
257         long id = ContentUris.parseId(target);
258         ContentResolver cr = context.getContentResolver();
259         String whereClause = Images.ImageColumns._ID + "=" + Long.toString(id);
260         try {
261             Cursor cursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, CacheService.PROJECTION_IMAGES, whereClause, null, null);
262             if (cursor != null) {
263                 if (cursor.moveToFirst()) {
264                     item = new MediaItem();
265                     CacheService.populateMediaItemFromCursor(item, cr, cursor, Images.Media.EXTERNAL_CONTENT_URI.toString() + "/");
266                 }
267                 cursor.close();
268                 cursor = null;
269             }
270         } catch (Exception e) {
271             // If the database operation failed for any reason.
272             ;
273         }
274         return item;
275     }
276
277     public static MediaItem createMediaItemFromFileUri(Context context, String fileUri) {
278         MediaItem item = null;
279         String filepath = new File(URI.create(fileUri)).toString();
280         ContentResolver cr = context.getContentResolver();
281         long bucketId = SingleDataSource.parseBucketIdFromFileUri(fileUri);
282         String whereClause = Images.ImageColumns.BUCKET_ID + "=" + bucketId + " AND " + Images.ImageColumns.DATA + "='" + filepath
283                 + "'";
284         try {
285             Cursor cursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, CacheService.PROJECTION_IMAGES, whereClause, null, null);
286             if (cursor != null) {
287                 if (cursor.moveToFirst()) {
288                     item = new MediaItem();
289                     CacheService.populateMediaItemFromCursor(item, cr, cursor, Images.Media.EXTERNAL_CONTENT_URI.toString() + "/");
290                 }
291                 cursor.close();
292                 cursor = null;
293             }
294         } catch (Exception e) {
295             // If the database operation failed for any reason.
296             ;
297         }
298         return item;
299     }
300 }