OSDN Git Service

0c8ad6dfb26482f28ab94077b70080c0312f23a5
[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                 MediaSet mediaSet = feed.getCurrentSet();
70                 if (mediaSet != null) {
71                     CacheService.markDirtyImmediate(mediaSet.mId);
72                     refreshUI(feed, mediaSet.mId);
73                 }
74                 CacheService.senseDirty(mContext, new CacheService.Observer() {
75                     public void onChange(long[] ids) {
76                         if (ids != null) {
77                             int numLongs = ids.length;
78                             for (int i = 0; i < numLongs; ++i) {
79                                 refreshUI(feed, ids[i]);
80                             }
81                         }
82                     }
83                 });
84             }
85         };
86
87         // Start listening.
88         Uri uriImages = Images.Media.EXTERNAL_CONTENT_URI;
89         Uri uriVideos = Video.Media.EXTERNAL_CONTENT_URI;
90         ContentResolver cr = mContext.getContentResolver();
91         mObserver = observer;
92         cr.registerContentObserver(uriImages, false, observer);
93         cr.registerContentObserver(uriVideos, false, observer);
94         sObserverActive = true;
95     }
96
97     public void shutdown() {
98         if (ImageManager.isMediaScannerScanning(mContext.getContentResolver())) {
99             stopListeners();
100         }
101     }
102
103     private void stopListeners() {
104         ContentResolver cr = mContext.getContentResolver();
105         if (mObserver != null) {
106             cr.unregisterContentObserver(mObserver);
107         }
108         sObserverActive = false;
109     }
110
111     protected void refreshUI(MediaFeed feed, long setIdToUse) {
112         if (setIdToUse == Shared.INVALID) {
113             return;
114         }
115         if (feed.getMediaSet(setIdToUse) == null) {
116             MediaSet mediaSet = feed.addMediaSet(setIdToUse, this);
117             if (setIdToUse == CAMERA_BUCKET_ID) {
118                 mediaSet.mName = CAMERA_STRING;
119             } else if (setIdToUse == DOWNLOAD_BUCKET_ID) {
120                 mediaSet.mName = DOWNLOAD_STRING;
121             }
122             mediaSet.generateTitle(true);
123         } else {
124             MediaSet mediaSet = feed.replaceMediaSet(setIdToUse, this);
125             Log.i(TAG, "Replacing mediaset " + mediaSet.mName + " id " + setIdToUse + " current Id " + mediaSet.mId);
126             if (setIdToUse == CAMERA_BUCKET_ID) {
127                 mediaSet.mName = CAMERA_STRING;
128             } else if (setIdToUse == DOWNLOAD_BUCKET_ID) {
129                 mediaSet.mName = DOWNLOAD_STRING;
130             }
131             mediaSet.generateTitle(true);
132         }
133     }
134
135     public void loadItemsForSet(final MediaFeed feed, final MediaSet parentSet, int rangeStart, int rangeEnd) {
136         // Quick load from the cache.
137         if (mContext == null || parentSet == null) {
138             return;
139         }
140         loadMediaItemsIntoMediaFeed(feed, parentSet, rangeStart, rangeEnd);
141     }
142
143     private void loadMediaItemsIntoMediaFeed(final MediaFeed mediaFeed, final MediaSet set, int rangeStart, int rangeEnd) {
144         if (rangeEnd - rangeStart < 0) {
145             return;
146         }
147         CacheService.loadMediaItemsIntoMediaFeed(mediaFeed, set, rangeStart, rangeEnd, !mDisableImages, !mDisableVideos);
148         if (set.mId == CAMERA_BUCKET_ID) {
149             mediaFeed.moveSetToFront(set);
150         }
151     }
152
153     public boolean performOperation(final int operation, final ArrayList<MediaBucket> mediaBuckets, final Object data) {
154         int numBuckets = mediaBuckets.size();
155         ContentResolver cr = mContext.getContentResolver();
156         switch (operation) {
157         case MediaFeed.OPERATION_DELETE:
158             for (int i = 0; i < numBuckets; ++i) {
159                 MediaBucket bucket = mediaBuckets.get(i);
160                 MediaSet set = bucket.mediaSet;
161                 ArrayList<MediaItem> items = bucket.mediaItems;
162                 if (set != null && items == null) {
163                     // Remove the entire bucket.
164                     final Uri uriImages = Images.Media.EXTERNAL_CONTENT_URI;
165                     final Uri uriVideos = Video.Media.EXTERNAL_CONTENT_URI;
166                     final String whereImages = Images.ImageColumns.BUCKET_ID + "=" + Long.toString(set.mId);
167                     final String whereVideos = Video.VideoColumns.BUCKET_ID + "=" + Long.toString(set.mId);
168                     cr.delete(uriImages, whereImages, null);
169                     cr.delete(uriVideos, whereVideos, null);
170                     CacheService.markDirty(mContext);
171                 }
172                 if (set != null && items != null) {
173                     // We need to remove these items from the set.
174                     int numItems = items.size();
175                     try {
176                         for (int j = 0; j < numItems; ++j) {
177                             MediaItem item = items.get(j);
178                             cr.delete(Uri.parse(item.mContentUri), null, null);
179                         }
180                     } catch (Exception e) {
181                         // If the database operation failed for any reason.
182                         ;
183                     }
184                     set.updateNumExpectedItems();
185                     set.generateTitle(true);
186                     CacheService.markDirty(mContext, set.mId);
187                 }
188             }
189             break;
190         case MediaFeed.OPERATION_ROTATE:
191             for (int i = 0; i < numBuckets; ++i) {
192                 MediaBucket bucket = mediaBuckets.get(i);
193                 ArrayList<MediaItem> items = bucket.mediaItems;
194                 if (items == null) {
195                     continue;
196                 }
197                 float angleToRotate = ((Float) data).floatValue();
198                 if (angleToRotate == 0) {
199                     return true;
200                 }
201                 int numItems = items.size();
202                 for (int j = 0; j < numItems; ++j) {
203                     rotateItem(items.get(j), angleToRotate);
204                 }
205             }
206             break;
207         }
208         return true;
209     }
210
211     private void rotateItem(final MediaItem item, float angleToRotate) {
212         ContentResolver cr = mContext.getContentResolver();
213         try {
214             int currentOrientation = (int) item.mRotation;
215             angleToRotate += currentOrientation;
216             float rotation = Shared.normalizePositive(angleToRotate);
217             String rotationString = Integer.toString((int) rotation);
218
219             // Update the database entry.
220             ContentValues values = new ContentValues();
221             values.put(Images.ImageColumns.ORIENTATION, rotationString);
222             try {
223                 cr.update(Uri.parse(item.mContentUri), values, null, null);
224             } catch (Exception e) {
225                 // If the database operation fails for any reason.
226                 ;
227             }
228
229             // Update the file EXIF information.
230             Uri uri = Uri.parse(item.mContentUri);
231             String uriScheme = uri.getScheme();
232             if (uriScheme.equals("file")) {
233                 ExifInterface exif = new ExifInterface(uri.getPath());
234                 exif.setAttribute(ExifInterface.TAG_ORIENTATION, Integer.toString(Shared.degreesToExifOrientation(rotation)));
235                 exif.saveAttributes();
236             }
237
238             // Invalidate the cache entry.
239             CacheService.markDirty(mContext, item.mParentMediaSet.mId);
240
241             // Update the object representation of the item.
242             item.mRotation = rotation;
243         } catch (Exception e) {
244             // System.out.println("Apparently not a JPEG");
245         }
246     }
247
248     public DiskCache getThumbnailCache() {
249         return sThumbnailCache;
250     }
251
252     public static MediaItem createMediaItemFromUri(Context context, Uri target) {
253         MediaItem item = null;
254         long id = ContentUris.parseId(target);
255         ContentResolver cr = context.getContentResolver();
256         String whereClause = Images.ImageColumns._ID + "=" + Long.toString(id);
257         try {
258             Cursor cursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, CacheService.PROJECTION_IMAGES, whereClause, null, null);
259             if (cursor != null) {
260                 if (cursor.moveToFirst()) {
261                     item = new MediaItem();
262                     CacheService.populateMediaItemFromCursor(item, cr, cursor, Images.Media.EXTERNAL_CONTENT_URI.toString() + "/");
263                 }
264                 cursor.close();
265                 cursor = null;
266             }
267         } catch (Exception e) {
268             // If the database operation failed for any reason.
269             ;
270         }
271         return item;
272     }
273
274     public static MediaItem createMediaItemFromFileUri(Context context, String fileUri) {
275         MediaItem item = null;
276         String filepath = new File(URI.create(fileUri)).toString();
277         ContentResolver cr = context.getContentResolver();
278         long bucketId = SingleDataSource.parseBucketIdFromFileUri(fileUri);
279         String whereClause = Images.ImageColumns.BUCKET_ID + "=" + bucketId + " AND " + Images.ImageColumns.DATA + "='" + filepath
280                 + "'";
281         try {
282             Cursor cursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, CacheService.PROJECTION_IMAGES, whereClause, null, null);
283             if (cursor != null) {
284                 if (cursor.moveToFirst()) {
285                     item = new MediaItem();
286                     CacheService.populateMediaItemFromCursor(item, cr, cursor, Images.Media.EXTERNAL_CONTENT_URI.toString() + "/");
287                 }
288                 cursor.close();
289                 cursor = null;
290             }
291         } catch (Exception e) {
292             // If the database operation failed for any reason.
293             ;
294         }
295         return item;
296     }
297 }