LocalImage.java revision f8a39c644637a15b9291eb9299762b8cf91cd76a
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.annotation.TargetApi;
20import android.content.ContentResolver;
21import android.content.ContentValues;
22import android.content.Context;
23import android.database.Cursor;
24import android.graphics.Bitmap;
25import android.graphics.BitmapFactory;
26import android.graphics.BitmapRegionDecoder;
27import android.media.ExifInterface;
28import android.net.Uri;
29import android.os.Build;
30import android.provider.MediaStore.Images;
31import android.provider.MediaStore.Images.ImageColumns;
32import android.provider.MediaStore.MediaColumns;
33import android.util.Log;
34
35import com.android.gallery3d.app.GalleryApp;
36import com.android.gallery3d.common.ApiHelper;
37import com.android.gallery3d.common.BitmapUtils;
38import com.android.gallery3d.util.GalleryUtils;
39import com.android.gallery3d.util.LightCycleHelper;
40import com.android.gallery3d.util.ThreadPool.Job;
41import com.android.gallery3d.util.ThreadPool.JobContext;
42import com.android.gallery3d.util.UpdateHelper;
43
44import java.io.File;
45import java.io.IOException;
46
47// LocalImage represents an image in the local storage.
48public class LocalImage extends LocalMediaItem {
49    private static final String TAG = "LocalImage";
50
51    static final Path ITEM_PATH = Path.fromString("/local/image/item");
52
53    // Must preserve order between these indices and the order of the terms in
54    // the following PROJECTION array.
55    private static final int INDEX_ID = 0;
56    private static final int INDEX_CAPTION = 1;
57    private static final int INDEX_MIME_TYPE = 2;
58    private static final int INDEX_LATITUDE = 3;
59    private static final int INDEX_LONGITUDE = 4;
60    private static final int INDEX_DATE_TAKEN = 5;
61    private static final int INDEX_DATE_ADDED = 6;
62    private static final int INDEX_DATE_MODIFIED = 7;
63    private static final int INDEX_DATA = 8;
64    private static final int INDEX_ORIENTATION = 9;
65    private static final int INDEX_BUCKET_ID = 10;
66    private static final int INDEX_SIZE = 11;
67    private static final int INDEX_WIDTH = 12;
68    private static final int INDEX_HEIGHT = 13;
69
70    static final String[] PROJECTION =  {
71            ImageColumns._ID,           // 0
72            ImageColumns.TITLE,         // 1
73            ImageColumns.MIME_TYPE,     // 2
74            ImageColumns.LATITUDE,      // 3
75            ImageColumns.LONGITUDE,     // 4
76            ImageColumns.DATE_TAKEN,    // 5
77            ImageColumns.DATE_ADDED,    // 6
78            ImageColumns.DATE_MODIFIED, // 7
79            ImageColumns.DATA,          // 8
80            ImageColumns.ORIENTATION,   // 9
81            ImageColumns.BUCKET_ID,     // 10
82            ImageColumns.SIZE,          // 11
83            "0",                        // 12
84            "0"                         // 13
85    };
86
87    static {
88        updateWidthAndHeightProjection();
89    }
90
91    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
92    private static void updateWidthAndHeightProjection() {
93        if (ApiHelper.HAS_MEDIA_COLUMNS_WIDTH_AND_HEIGHT) {
94            PROJECTION[INDEX_WIDTH] = MediaColumns.WIDTH;
95            PROJECTION[INDEX_HEIGHT] = MediaColumns.HEIGHT;
96        }
97    }
98
99    private final GalleryApp mApplication;
100
101    public int rotation;
102
103    private boolean mUsePanoramaViewer;
104    private boolean mUsePanoramaViewerInitialized;
105
106    public LocalImage(Path path, GalleryApp application, Cursor cursor) {
107        super(path, nextVersionNumber());
108        mApplication = application;
109        loadFromCursor(cursor);
110    }
111
112    public LocalImage(Path path, GalleryApp application, int id) {
113        super(path, nextVersionNumber());
114        mApplication = application;
115        ContentResolver resolver = mApplication.getContentResolver();
116        Uri uri = Images.Media.EXTERNAL_CONTENT_URI;
117        Cursor cursor = LocalAlbum.getItemCursor(resolver, uri, PROJECTION, id);
118        if (cursor == null) {
119            throw new RuntimeException("cannot get cursor for: " + path);
120        }
121        try {
122            if (cursor.moveToNext()) {
123                loadFromCursor(cursor);
124            } else {
125                throw new RuntimeException("cannot find data for: " + path);
126            }
127        } finally {
128            cursor.close();
129        }
130    }
131
132    private void loadFromCursor(Cursor cursor) {
133        id = cursor.getInt(INDEX_ID);
134        caption = cursor.getString(INDEX_CAPTION);
135        mimeType = cursor.getString(INDEX_MIME_TYPE);
136        latitude = cursor.getDouble(INDEX_LATITUDE);
137        longitude = cursor.getDouble(INDEX_LONGITUDE);
138        dateTakenInMs = cursor.getLong(INDEX_DATE_TAKEN);
139        filePath = cursor.getString(INDEX_DATA);
140        rotation = cursor.getInt(INDEX_ORIENTATION);
141        bucketId = cursor.getInt(INDEX_BUCKET_ID);
142        fileSize = cursor.getLong(INDEX_SIZE);
143        width = cursor.getInt(INDEX_WIDTH);
144        height = cursor.getInt(INDEX_HEIGHT);
145    }
146
147    @Override
148    protected boolean updateFromCursor(Cursor cursor) {
149        UpdateHelper uh = new UpdateHelper();
150        id = uh.update(id, cursor.getInt(INDEX_ID));
151        caption = uh.update(caption, cursor.getString(INDEX_CAPTION));
152        mimeType = uh.update(mimeType, cursor.getString(INDEX_MIME_TYPE));
153        latitude = uh.update(latitude, cursor.getDouble(INDEX_LATITUDE));
154        longitude = uh.update(longitude, cursor.getDouble(INDEX_LONGITUDE));
155        dateTakenInMs = uh.update(
156                dateTakenInMs, cursor.getLong(INDEX_DATE_TAKEN));
157        dateAddedInSec = uh.update(
158                dateAddedInSec, cursor.getLong(INDEX_DATE_ADDED));
159        dateModifiedInSec = uh.update(
160                dateModifiedInSec, cursor.getLong(INDEX_DATE_MODIFIED));
161        filePath = uh.update(filePath, cursor.getString(INDEX_DATA));
162        rotation = uh.update(rotation, cursor.getInt(INDEX_ORIENTATION));
163        bucketId = uh.update(bucketId, cursor.getInt(INDEX_BUCKET_ID));
164        fileSize = uh.update(fileSize, cursor.getLong(INDEX_SIZE));
165        width = uh.update(width, cursor.getInt(INDEX_WIDTH));
166        height = uh.update(height, cursor.getInt(INDEX_HEIGHT));
167        return uh.isUpdated();
168    }
169
170    @Override
171    public Job<Bitmap> requestImage(int type) {
172        return new LocalImageRequest(mApplication, mPath, type, filePath);
173    }
174
175    public static class LocalImageRequest extends ImageCacheRequest {
176        private String mLocalFilePath;
177
178        LocalImageRequest(GalleryApp application, Path path, int type,
179                String localFilePath) {
180            super(application, path, type, MediaItem.getTargetSize(type));
181            mLocalFilePath = localFilePath;
182        }
183
184        @Override
185        public Bitmap onDecodeOriginal(JobContext jc, final int type) {
186            BitmapFactory.Options options = new BitmapFactory.Options();
187            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
188            int targetSize = MediaItem.getTargetSize(type);
189
190            // try to decode from JPEG EXIF
191            if (type == MediaItem.TYPE_MICROTHUMBNAIL) {
192                ExifInterface exif = null;
193                byte [] thumbData = null;
194                try {
195                    exif = new ExifInterface(mLocalFilePath);
196                    if (exif != null) {
197                        thumbData = exif.getThumbnail();
198                    }
199                } catch (Throwable t) {
200                    Log.w(TAG, "fail to get exif thumb", t);
201                }
202                if (thumbData != null) {
203                    Bitmap bitmap = DecodeUtils.decodeIfBigEnough(
204                            jc, thumbData, options, targetSize);
205                    if (bitmap != null) return bitmap;
206                }
207            }
208
209            return DecodeUtils.decodeThumbnail(jc, mLocalFilePath, options, targetSize, type);
210        }
211    }
212
213    @Override
214    public Job<BitmapRegionDecoder> requestLargeImage() {
215        return new LocalLargeImageRequest(filePath);
216    }
217
218    public static class LocalLargeImageRequest
219            implements Job<BitmapRegionDecoder> {
220        String mLocalFilePath;
221
222        public LocalLargeImageRequest(String localFilePath) {
223            mLocalFilePath = localFilePath;
224        }
225
226        @Override
227        public BitmapRegionDecoder run(JobContext jc) {
228            return DecodeUtils.createBitmapRegionDecoder(jc, mLocalFilePath, false);
229        }
230    }
231
232    @Override
233    public int getSupportedOperations() {
234        int operation = SUPPORT_DELETE | SUPPORT_SHARE | SUPPORT_CROP
235                | SUPPORT_SETAS | SUPPORT_EDIT | SUPPORT_INFO;
236        if (BitmapUtils.isSupportedByRegionDecoder(mimeType)) {
237            operation |= SUPPORT_FULL_IMAGE;
238        }
239
240        if (BitmapUtils.isRotationSupported(mimeType)) {
241            operation |= SUPPORT_ROTATE;
242        }
243
244        if (GalleryUtils.isValidLocation(latitude, longitude)) {
245            operation |= SUPPORT_SHOW_ON_MAP;
246        }
247
248        if (usePanoramaViewer()) {
249            operation |= SUPPORT_VIEW_PANORAMA;
250        }
251        return operation;
252    }
253
254    @Override
255    public void delete() {
256        GalleryUtils.assertNotInRenderThread();
257        Uri baseUri = Images.Media.EXTERNAL_CONTENT_URI;
258        mApplication.getContentResolver().delete(baseUri, "_id=?",
259                new String[]{String.valueOf(id)});
260        mApplication.getDataManager().broadcastLocalDeletion();
261    }
262
263    private static String getExifOrientation(int orientation) {
264        switch (orientation) {
265            case 0:
266                return String.valueOf(ExifInterface.ORIENTATION_NORMAL);
267            case 90:
268                return String.valueOf(ExifInterface.ORIENTATION_ROTATE_90);
269            case 180:
270                return String.valueOf(ExifInterface.ORIENTATION_ROTATE_180);
271            case 270:
272                return String.valueOf(ExifInterface.ORIENTATION_ROTATE_270);
273            default:
274                throw new AssertionError("invalid: " + orientation);
275        }
276    }
277
278    @Override
279    public void rotate(int degrees) {
280        GalleryUtils.assertNotInRenderThread();
281        Uri baseUri = Images.Media.EXTERNAL_CONTENT_URI;
282        ContentValues values = new ContentValues();
283        int rotation = (this.rotation + degrees) % 360;
284        if (rotation < 0) rotation += 360;
285
286        if (mimeType.equalsIgnoreCase("image/jpeg")) {
287            try {
288                ExifInterface exif = new ExifInterface(filePath);
289                exif.setAttribute(ExifInterface.TAG_ORIENTATION,
290                        getExifOrientation(rotation));
291                exif.saveAttributes();
292            } catch (IOException e) {
293                Log.w(TAG, "cannot set exif data: " + filePath);
294            }
295
296            // We need to update the filesize as well
297            fileSize = new File(filePath).length();
298            values.put(Images.Media.SIZE, fileSize);
299        }
300
301        values.put(Images.Media.ORIENTATION, rotation);
302        mApplication.getContentResolver().update(baseUri, values, "_id=?",
303                new String[]{String.valueOf(id)});
304    }
305
306    @Override
307    public Uri getContentUri() {
308        Uri baseUri = Images.Media.EXTERNAL_CONTENT_URI;
309        return baseUri.buildUpon().appendPath(String.valueOf(id)).build();
310    }
311
312    @Override
313    public int getMediaType() {
314        return MEDIA_TYPE_IMAGE;
315    }
316
317    @Override
318    public MediaDetails getDetails() {
319        MediaDetails details = super.getDetails();
320        details.addDetail(MediaDetails.INDEX_ORIENTATION, Integer.valueOf(rotation));
321        if (MIME_TYPE_JPEG.equals(mimeType)) {
322            // ExifInterface returns incorrect values for photos in other format.
323            // For example, the width and height of an webp images is always '0'.
324            MediaDetails.extractExifInfo(details, filePath);
325        }
326        return details;
327    }
328
329    @Override
330    public int getRotation() {
331        return rotation;
332    }
333
334    @Override
335    public int getWidth() {
336        return width;
337    }
338
339    @Override
340    public int getHeight() {
341        return height;
342    }
343
344    @Override
345    public String getFilePath() {
346        return filePath;
347    }
348
349    @Override
350    public boolean usePanoramaViewer() {
351        if (!mUsePanoramaViewerInitialized) {
352            Context context = mApplication.getAndroidContext();
353            mUsePanoramaViewer = LightCycleHelper.hasLightCycleView(context)
354                    && LightCycleHelper.isPanorama(mApplication.getContentResolver(),
355                            getContentUri());
356            mUsePanoramaViewerInitialized = true;
357        }
358        return mUsePanoramaViewer;
359    }
360}
361