summaryrefslogtreecommitdiffstats
path: root/src/com/android/dreams/phototable/PhotoSource.java
blob: d05eaceff5c68289cc8b1fd3295e1f86b497a264 (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
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.dreams.phototable;

import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Random;

/**
 * Picks a random image from a source of photos.
 */
public abstract class PhotoSource {
    private static final String TAG = "PhotoTable.PhotoSource";
    private static final boolean DEBUG = false;

    // This should be large enough for BitmapFactory to decode the header so
    // that we can mark and reset the input stream to avoid duplicate network i/o
    private static final int BUFFER_SIZE = 32 * 1024;

    public class ImageData {
        public String id;
        public String url;
        public int orientation;

        protected String albumId;
        protected Cursor cursor;
        protected int position;
        protected Uri uri;

        InputStream getStream(int longSide) {
            return PhotoSource.this.getStream(this, longSide);
        }
        ImageData naturalNext() {
            return PhotoSource.this.naturalNext(this);
        }
        ImageData naturalPrevious() {
            return PhotoSource.this.naturalPrevious(this);
        }
        public void donePaging() {
            PhotoSource.this.donePaging(this);
        }
    }

    public class AlbumData {
        public String id;
        public String title;
        public String thumbnailUrl;
        public String account;
        public long updated;

        public String getType() {
            String type = PhotoSource.this.getClass().getName();
            log(TAG, "type is " + type);
            return type;
        }
    }

    private final LinkedList<ImageData> mImageQueue;
    private final int mMaxQueueSize;
    private final float mMaxCropRatio;
    private final int mBadImageSkipLimit;
    private final PhotoSource mFallbackSource;
    private final HashMap<Bitmap, ImageData> mImageMap;

    protected final Context mContext;
    protected final Resources mResources;
    protected final Random mRNG;
    protected final AlbumSettings mSettings;
    protected final ContentResolver mResolver;

    protected String mSourceName;

    public PhotoSource(Context context, SharedPreferences settings) {
        this(context, settings, new StockSource(context, settings));
    }

    public PhotoSource(Context context, SharedPreferences settings, PhotoSource fallbackSource) {
        mSourceName = TAG;
        mContext = context;
        mSettings = AlbumSettings.getAlbumSettings(settings);
        mResolver = mContext.getContentResolver();
        mResources = context.getResources();
        mImageQueue = new LinkedList<ImageData>();
        mMaxQueueSize = mResources.getInteger(R.integer.image_queue_size);
        mMaxCropRatio = mResources.getInteger(R.integer.max_crop_ratio) / 1000000f;
        mBadImageSkipLimit = mResources.getInteger(R.integer.bad_image_skip_limit);
        mImageMap = new HashMap<Bitmap, ImageData>();
        mRNG = new Random();
        mFallbackSource = fallbackSource;
    }

    protected void fillQueue() {
        log(TAG, "filling queue");
        mImageQueue.addAll(findImages(mMaxQueueSize - mImageQueue.size()));
        Collections.shuffle(mImageQueue);
        log(TAG, "queue contains: " + mImageQueue.size() + " items.");
    }

    public Bitmap next(BitmapFactory.Options options, int longSide, int shortSide) {
        log(TAG, "decoding a picasa resource to " +  longSide + ", " + shortSide);
        Bitmap image = null;
        ImageData imageData = null;
        int tries = 0;

        while (image == null && tries < mBadImageSkipLimit) {
            synchronized(mImageQueue) {
                if (mImageQueue.isEmpty()) {
                    fillQueue();
                }
                imageData = mImageQueue.poll();
            }
            if (imageData != null) {
                image = load(imageData, options, longSide, shortSide);
                mImageMap.put(image, imageData);
                imageData = null;
            }

            tries++;
        }

        if (image == null && mFallbackSource != null) {
            image = load((ImageData) mFallbackSource.findImages(1).toArray()[0],
                    options, longSide, shortSide);
        }

        return image;
    }

    public Bitmap load(ImageData data, BitmapFactory.Options options, int longSide, int shortSide) {
        log(TAG, "decoding photo resource to " +  longSide + ", " + shortSide);
        InputStream is = data.getStream(longSide);

        Bitmap image = null;
        try {
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(BUFFER_SIZE);

            options.inJustDecodeBounds = true;
            options.inSampleSize = 1;
            image = BitmapFactory.decodeStream(new BufferedInputStream(bis), null, options);
            int rawLongSide = Math.max(options.outWidth, options.outHeight);
            int rawShortSide = Math.min(options.outWidth, options.outHeight);
            log(TAG, "I see bounds of " +  rawLongSide + ", " + rawShortSide);

            if (rawLongSide != -1 && rawShortSide != -1) {
                float insideRatio = Math.max((float) longSide / (float) rawLongSide,
                                             (float) shortSide / (float) rawShortSide);
                float outsideRatio = Math.max((float) longSide / (float) rawLongSide,
                                              (float) shortSide / (float) rawShortSide);
                float ratio = (outsideRatio / insideRatio < mMaxCropRatio ?
                               outsideRatio : insideRatio);

                while (ratio < 0.5) {
                    options.inSampleSize *= 2;
                    ratio *= 2;
                }

                log(TAG, "decoding with inSampleSize " +  options.inSampleSize);
                try {
                    bis.reset();
                } catch (IOException ioe) {
                    // start over, something went wrong and we read too far into the image.
                    bis.close();
                    is = data.getStream(longSide);
                    bis = new BufferedInputStream(is);
                    log(TAG, "resetting the stream");
                }
                options.inJustDecodeBounds = false;
                image = BitmapFactory.decodeStream(bis, null, options);
                rawLongSide = Math.max(options.outWidth, options.outHeight);
                rawShortSide = Math.max(options.outWidth, options.outHeight);
                if (image != null && rawLongSide != -1 && rawShortSide != -1) {
                    ratio = Math.max((float) longSide / (float) rawLongSide,
                            (float) shortSide / (float) rawShortSide);

                    if (Math.abs(ratio - 1.0f) > 0.001) {
                        log(TAG, "still too big, scaling down by " + ratio);
                        options.outWidth = (int) (ratio * options.outWidth);
                        options.outHeight = (int) (ratio * options.outHeight);

                        image = Bitmap.createScaledBitmap(image,
                                options.outWidth, options.outHeight,
                                true);
                    }

                    if (data.orientation != 0) {
                        log(TAG, "rotated by " + data.orientation + ": fixing");
                        Matrix matrix = new Matrix();
                        matrix.setRotate(data.orientation,
                                (float) Math.floor(image.getWidth() / 2f),
                                (float) Math.floor(image.getHeight() / 2f));
                        image = Bitmap.createBitmap(image, 0, 0,
                                                    options.outWidth, options.outHeight,
                                                    matrix, true);
                        if (data.orientation == 90 || data.orientation == 270) {
                            int tmp = options.outWidth;
                            options.outWidth = options.outHeight;
                            options.outHeight = tmp;
                        }
                    }

                    log(TAG, "returning bitmap " + image.getWidth() + ", " + image.getHeight());
                } else {
                    image = null;
                }
            } else {
                image = null;
            }
            if (image == null) {
                log(TAG, "Stream decoding failed with no error" +
                        (options.mCancel ? " due to cancelation." : "."));
            }
        } catch (OutOfMemoryError ome) {
            log(TAG, "OUT OF MEMORY: " + ome);
            image = null;
        } catch (FileNotFoundException fnf) {
            log(TAG, "file not found: " + fnf);
            image = null;
        } catch (IOException ioe) {
            log(TAG, "i/o exception: " + ioe);
            image = null;
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Throwable t) {
                log(TAG, "close fail: " + t.toString());
            }
        }

        return image;
    }

    public void setSeed(long seed) {
        mRNG.setSeed(seed);
    }

    protected static void log(String tag, String message) {
        if (DEBUG) {
            Log.i(tag, message);
        }
    }

    protected int pickRandomStart(int total, int max) {
        if (max >= total) {
            return -1;
        } else {
            return (mRNG.nextInt() % (total - max)) - 1;
        }
    }

    public Bitmap naturalNext(Bitmap current, BitmapFactory.Options options,
            int longSide, int shortSide) {
        Bitmap image = null;
        ImageData data = mImageMap.get(current);
        if (data != null) {
          ImageData next = data.naturalNext();
          if (next != null) {
            image = load(next, options, longSide, shortSide);
            mImageMap.put(image, next);
          }
        }
        return image;
    }

    public Bitmap naturalPrevious(Bitmap current, BitmapFactory.Options options,
            int longSide, int shortSide) {
        Bitmap image = null;
        ImageData data = mImageMap.get(current);
        if (current != null) {
          ImageData prev = data.naturalPrevious();
          if (prev != null) {
            image = load(prev, options, longSide, shortSide);
            mImageMap.put(image, prev);
          }
        }
        return image;
    }

    public void donePaging(Bitmap current) {
        ImageData data = mImageMap.get(current);
        if (data != null) {
            data.donePaging();
        }
    }

    public void recycle(Bitmap trash) {
        if (trash != null) {
            mImageMap.remove(trash);
            trash.recycle();
        }
    }

    protected abstract InputStream getStream(ImageData data, int longSide);
    protected abstract Collection<ImageData> findImages(int howMany);
    protected abstract ImageData naturalNext(ImageData current);
    protected abstract ImageData naturalPrevious(ImageData current);
    protected abstract void donePaging(ImageData current);

    public abstract Collection<AlbumData> findAlbums();
}