summaryrefslogtreecommitdiffstats
path: root/src/com/android/mail/photomanager/AttachmentPreviewsManager.java
blob: dc584f34e5b5389c1a1588662009923d55e13a63 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package com.android.mail.photomanager;

import com.android.mail.photomanager.BitmapUtil.InputStreamFactory;
import com.android.mail.providers.Attachment;
import com.android.mail.providers.UIProvider;
import com.android.mail.providers.UIProvider.AttachmentRendition;
import com.android.mail.ui.DividedImageCanvas;
import com.android.mail.ui.ImageCanvas.Dimensions;
import com.android.mail.utils.Utils;
import com.google.common.base.Objects;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Pair;

import com.android.mail.ui.ImageCanvas;
import com.android.mail.utils.LogUtils;
import com.google.common.primitives.Longs;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Asynchronously loads attachment image previews and maintains a cache of
 * photos.
 */
public class AttachmentPreviewsManager extends PhotoManager {

    private static final DefaultImageProvider sDefaultImageProvider
            = new AttachmentPreviewsDefaultProvider();
    private final Map<Object, AttachmentPreviewsManagerCallback> mCallbacks;

    public static int generateHash(ImageCanvas view, Object key) {
        return Objects.hashCode(view, key);
    }

    public static String transformKeyToUri(Object key) {
        return (String) ((Pair)key).second;
    }

    public AttachmentPreviewsManager(Context context) {
        super(context);
        mCallbacks = new HashMap<Object, AttachmentPreviewsManagerCallback>();
    }

    public void loadThumbnail(PhotoIdentifier id, ImageCanvas view, Dimensions dimensions,
            AttachmentPreviewsManagerCallback callback) {
        mCallbacks.put(id.getKey(), callback);
        super.loadThumbnail(id, view, dimensions);
    }

    @Override
    protected DefaultImageProvider getDefaultImageProvider() {
        return sDefaultImageProvider;
    }

    @Override
    protected int getHash(PhotoIdentifier id, ImageCanvas view) {
        return generateHash(view, id.getKey());
    }

    @Override
    protected PhotoLoaderThread getLoaderThread(ContentResolver contentResolver) {
        return new AttachmentPreviewsLoaderThread(contentResolver);
    }

    @Override
    protected void onImageDrawn(Request request, boolean success) {
        Object key = request.getKey();
        if (mCallbacks.containsKey(key)) {
            AttachmentPreviewsManagerCallback callback = mCallbacks.get(key);
            callback.onImageDrawn(request.getKey(), success);

            if (success) {
                mCallbacks.remove(key);
            }
        }
    }

    @Override
    protected boolean isSizeCompatible(int prevWidth, int prevHeight, int newWidth, int newHeight) {
        float ratio = (float) newWidth / prevWidth;
        boolean previousRequestSmaller = newWidth > prevWidth
                || newWidth > prevWidth * ratio
                || newHeight > prevHeight * ratio;
        return !previousRequestSmaller;
    }

    public static class AttachmentPreviewIdentifier extends PhotoIdentifier {
        public final String uri;
        public final int rendition;
        // conversationId and index used for sorting requests
        long conversationId;
        public int index;

        /**
         * <RENDITION, URI>
         */
        private Pair<Integer, String> mKey;

        public AttachmentPreviewIdentifier(String uri, int rendition, long conversationId,
                int index) {
            this.uri = uri;
            this.rendition = rendition;
            this.conversationId = conversationId;
            this.index = index;
            mKey = new Pair<Integer, String>(rendition, uri) {
                @Override
                public String toString() {
                    return "<" + first + ", " + second + ">";
                }
            };
        }

        @Override
        public boolean isValid() {
            return !TextUtils.isEmpty(uri) && rendition >= AttachmentRendition.SIMPLE;
        }

        @Override
        public Object getKey() {
            return mKey;
        }

        @Override
        public Object getKeyToShowInsteadOfDefault() {
            return new AttachmentPreviewIdentifier(uri, rendition - 1, conversationId, index)
                    .getKey();
        }

        @Override
        public int hashCode() {
            int hash = 17;
            hash = 31 * hash + (uri != null ? uri.hashCode() : 0);
            hash = 31 * hash + rendition;
            hash = 31 * hash + Longs.hashCode(conversationId);
            hash = 31 * hash + index;
            return hash;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            AttachmentPreviewIdentifier that = (AttachmentPreviewIdentifier) o;

            if (rendition != that.rendition) {
                return false;
            }
            if (uri != null ? !uri.equals(that.uri) : that.uri != null) {
                return false;
            }
            if (conversationId != that.conversationId) {
                return false;
            }
            if (index != that.index) {
                return false;
            }

            return true;
        }

        @Override
        public String toString() {
            return mKey.toString();
        }

        @Override
        public int compareTo(PhotoIdentifier another) {
            if (another instanceof AttachmentPreviewIdentifier) {
                AttachmentPreviewIdentifier anotherId = (AttachmentPreviewIdentifier) another;
                // We want to load SIMPLE images first because they are super fast
                if (rendition - anotherId.rendition != 0) {
                    return rendition - anotherId.rendition;
                }

                // Load images from later messages first (later messages appear on top of the list)
                if (anotherId.conversationId - conversationId != 0) {
                    return (anotherId.conversationId - conversationId) > 0 ? 1 : -1;
                }

                // Load images from left to right
                if (index - anotherId.index != 0) {
                    return index - anotherId.index;
                }

                return 0;
            } else {
                return -1;
            }
        }
    }

    protected class AttachmentPreviewsLoaderThread extends PhotoLoaderThread {

        public AttachmentPreviewsLoaderThread(ContentResolver resolver) {
            super(resolver);
        }

        @Override
        protected int getMaxBatchCount() {
            return 1;
        }

        @Override
        protected Map<String, BitmapHolder> loadPhotos(Collection<Request> requests) {
            final Map<String, BitmapHolder> photos = new HashMap<String, BitmapHolder>(
                    requests.size());

            LogUtils.d(TAG, "AttachmentPreviewsManager: starting batch load. Count: %d",
                    requests.size());
            for (final Request request : requests) {
                Utils.traceBeginSection("Setup load photo");
                final AttachmentPreviewIdentifier id = (AttachmentPreviewIdentifier) request
                        .getPhotoIdentifier();
                final Uri uri = Uri.parse(id.uri);
                // Get the attachment for this preview
                final Cursor cursor = getResolver()
                        .query(uri, UIProvider.ATTACHMENT_PROJECTION, null, null, null);
                if (cursor == null) {
                    Utils.traceEndSection();
                    continue;
                }
                Attachment attachment = null;
                try {
                    LogUtils.d(TAG, "AttachmentPreviewsManager: found %d attachments for uri %s",
                            cursor.getCount(), uri);
                    if (cursor.moveToFirst()) {
                        attachment = new Attachment(cursor);
                    }
                } finally {
                    cursor.close();
                }

                if (attachment == null) {
                    LogUtils.d(TAG, "AttachmentPreviewsManager: attachment not found for uri %s",
                            uri);
                    Utils.traceEndSection();
                    continue;
                }

                // Determine whether we load the SIMPLE or BEST image for this preview
                final Uri contentUri;
                if (id.rendition == UIProvider.AttachmentRendition.BEST) {
                    contentUri = attachment.contentUri;
                } else if (id.rendition == AttachmentRendition.SIMPLE) {
                    contentUri = attachment.thumbnailUri;
                } else {
                    LogUtils.d(TAG,
                            "AttachmentPreviewsManager: Cannot load rendition %d for uri %s",
                            id.rendition, uri);
                    Utils.traceEndSection();
                    continue;
                }

                LogUtils.d(TAG, "AttachmentPreviewsManager: attachments has contentUri %s",
                        contentUri);
                final InputStreamFactory factory = new InputStreamFactory() {
                    @Override
                    public InputStream newInputStream() {
                        try {
                            return getResolver().openInputStream(contentUri);
                        } catch (FileNotFoundException e) {
                            LogUtils.e(TAG,
                                    "AttachmentPreviewsManager: file not found for attachment %s."
                                            + " This may be due to the attachment not being "
                                            + "downloaded yet. But this shouldn't happen because "
                                            + "we check the state of the attachment downloads "
                                            + "before attempting to load it.",
                                    contentUri);
                            return null;
                        }
                    }
                };
                Utils.traceEndSection();

                Utils.traceBeginSection("Decode stream and crop");
                // todo:markwei read EXIF data for orientation
                // Crop it. I've seen that in real-world situations,
                // a 5.5MB image will be cropped down to about a 200KB image,
                // so this is definitely worth it.
                final Bitmap bitmap = BitmapUtil
                        .decodeStreamWithCenterCrop(factory, request.bitmapKey.w,
                                request.bitmapKey.h);
                Utils.traceEndSection();

                if (bitmap == null) {
                    LogUtils.w(TAG, "Unable to decode bitmap for contentUri %s", contentUri);
                    continue;
                }
                cacheBitmap(request.bitmapKey, bitmap);
                LogUtils.d(TAG,
                        "AttachmentPreviewsManager: finished loading attachment cropped size %db",
                        bitmap.getByteCount());
            }

            return photos;
        }
    }

    public static class AttachmentPreviewsDividedImageCanvas extends DividedImageCanvas {
        public AttachmentPreviewsDividedImageCanvas(Context context, InvalidateCallback callback) {
            super(context, callback);
        }

        @Override
        protected void drawVerticalDivider(int width, int height) {
            return; // do not draw vertical dividers
        }

        @Override
        protected boolean isPartialBitmapComplete() {
            return true; // images may not be loaded at the same time
        }

        @Override
        protected String transformKeyToDivisionId(Object key) {
            return transformKeyToUri(key);
        }
    }

    public static class AttachmentPreviewsDefaultProvider implements DefaultImageProvider {

        /**
         * All we need to do is clear the section. The ConversationItemView will draw the
         * progress bar.
         */
        @Override
        public void applyDefaultImage(PhotoIdentifier id, ImageCanvas view, int extent) {
            AttachmentPreviewsDividedImageCanvas dividedImageCanvas
                    = (AttachmentPreviewsDividedImageCanvas) view;
            dividedImageCanvas.clearDivisionImage(id.getKey());
        }
    }

    public interface AttachmentPreviewsManagerCallback {

        public void onImageDrawn(Object key, boolean success);
    }
}