summaryrefslogtreecommitdiffstats
path: root/src/com/android/dreams/phototable/PhotoSource.java
blob: 44e00d9c29e6bab23f12aa60c9f84e6f96d6eafb (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
/*
 * 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.provider.MediaStore;
import android.util.Log;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.util.Collection;
import java.util.Collections;
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 = true;

    // 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 = 128 * 1024;

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

        InputStream getStream() {
            return PhotoSource.this.getStream(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 PhotoSource mFallbackSource;

    protected final Context mContext;
    protected final Resources mResources;
    protected final Random mRNG;
    protected final SharedPreferences 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 = 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;
        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;

        if (mImageQueue.isEmpty()) {
            fillQueue();
        }

        if (!mImageQueue.isEmpty()) {
            image = load(mImageQueue.poll(), options, longSide, shortSide);
        }

        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();

        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);
                bis.reset();
                options.inJustDecodeBounds = false;
                image = BitmapFactory.decodeStream(bis, null, options);
                rawLongSide = Math.max(options.outWidth, options.outHeight);
                rawShortSide = Math.max(options.outWidth, options.outHeight);
                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");
                    if (data.orientation == 90 || data.orientation == 270) {
                        int tmp = options.outWidth;
                        options.outWidth = options.outHeight;
                        options.outHeight = tmp;
                    }
                    Matrix matrix = new Matrix();
                    matrix.setRotate(data.orientation,
                                     (float) image.getWidth() / 2,
                                     (float) image.getHeight() / 2);
                    image = Bitmap.createBitmap(image, 0, 0,
                                                options.outHeight, options.outWidth,
                                                matrix, true);
                }

                log(TAG, "returning bitmap " + image.getWidth() + ", " + image.getHeight());
            } else {
                    log(TAG, "decoding failed with no error: " + options.mCancel);
            }
        } catch (FileNotFoundException fnf) {
            log(TAG, "file not found: " + fnf);
        } catch (IOException ioe) {
            log(TAG, "i/o exception: " + ioe);
        } 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 abstract InputStream getStream(ImageData data);
    protected abstract Collection<ImageData> findImages(int howMany);
    public abstract Collection<AlbumData> findAlbums();
}