summaryrefslogtreecommitdiffstats
path: root/src/com/android/gallery3d/ui/AlbumSetSlidingWindow.java
blob: bf6e1dfc350b5ed6e2230214ffbd7b2ab6dcef51 (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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
/*
 * Copyright (C) 2010 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.gallery3d.ui;

import com.android.gallery3d.R;
import com.android.gallery3d.app.GalleryActivity;
import com.android.gallery3d.common.Utils;
import com.android.gallery3d.data.MediaItem;
import com.android.gallery3d.data.MediaSet;
import com.android.gallery3d.data.Path;
import com.android.gallery3d.ui.AlbumSetView.AlbumSetItem;
import com.android.gallery3d.util.Future;
import com.android.gallery3d.util.FutureListener;
import com.android.gallery3d.util.GalleryUtils;
import com.android.gallery3d.util.MediaSetUtils;
import com.android.gallery3d.util.ThreadPool;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Message;

public class AlbumSetSlidingWindow implements AlbumSetView.ModelListener {
    private static final String TAG = "GallerySlidingWindow";
    private static final int MSG_LOAD_BITMAP_DONE = 0;
    private static final int PLACEHOLDER_COLOR = 0xFF222222;

    public static interface Listener {
        public void onSizeChanged(int size);
        public void onContentInvalidated();
        public void onWindowContentChanged(
                int slot, AlbumSetItem old, AlbumSetItem update);
    }

    private final AlbumSetView.Model mSource;
    private int mSize;
    private AlbumSetView.LabelSpec mLabelSpec;

    private int mContentStart = 0;
    private int mContentEnd = 0;

    private int mActiveStart = 0;
    private int mActiveEnd = 0;

    private Listener mListener;

    private final MyAlbumSetItem mData[];
    private SelectionDrawer mSelectionDrawer;
    private final ColorTexture mWaitLoadingTexture;

    private SynchronizedHandler mHandler;
    private ThreadPool mThreadPool;

    private int mActiveRequestCount = 0;
    private String mLoadingLabel;
    private boolean mIsActive = false;

    private static class MyAlbumSetItem extends AlbumSetItem {
        public Path setPath;
        public int sourceType;
        public int cacheFlag;
        public int cacheStatus;
    }

    public AlbumSetSlidingWindow(GalleryActivity activity,
            AlbumSetView.LabelSpec labelSpec, SelectionDrawer drawer,
            AlbumSetView.Model source, int cacheSize) {
        source.setModelListener(this);
        mLabelSpec = labelSpec;
        mLoadingLabel = activity.getAndroidContext().getString(R.string.loading);
        mSource = source;
        mSelectionDrawer = drawer;
        mData = new MyAlbumSetItem[cacheSize];
        mSize = source.size();

        mWaitLoadingTexture = new ColorTexture(PLACEHOLDER_COLOR);
        mWaitLoadingTexture.setSize(1, 1);

        mHandler = new SynchronizedHandler(activity.getGLRoot()) {
            @Override
            public void handleMessage(Message message) {
                Utils.assertTrue(message.what == MSG_LOAD_BITMAP_DONE);
                ((GalleryDisplayItem) message.obj).onLoadBitmapDone();
            }
        };

        mThreadPool = activity.getThreadPool();
    }

    public void setSelectionDrawer(SelectionDrawer drawer) {
        mSelectionDrawer = drawer;
    }

    public void setListener(Listener listener) {
        mListener = listener;
    }

    public AlbumSetItem get(int slotIndex) {
        Utils.assertTrue(isActiveSlot(slotIndex),
                "invalid slot: %s outsides (%s, %s)",
                slotIndex, mActiveStart, mActiveEnd);
        return mData[slotIndex % mData.length];
    }

    public int size() {
        return mSize;
    }

    public boolean isActiveSlot(int slotIndex) {
        return slotIndex >= mActiveStart && slotIndex < mActiveEnd;
    }

    private void setContentWindow(int contentStart, int contentEnd) {
        if (contentStart == mContentStart && contentEnd == mContentEnd) return;

        if (contentStart >= mContentEnd || mContentStart >= contentEnd) {
            for (int i = mContentStart, n = mContentEnd; i < n; ++i) {
                freeSlotContent(i);
            }
            mSource.setActiveWindow(contentStart, contentEnd);
            for (int i = contentStart; i < contentEnd; ++i) {
                prepareSlotContent(i);
            }
        } else {
            for (int i = mContentStart; i < contentStart; ++i) {
                freeSlotContent(i);
            }
            for (int i = contentEnd, n = mContentEnd; i < n; ++i) {
                freeSlotContent(i);
            }
            mSource.setActiveWindow(contentStart, contentEnd);
            for (int i = contentStart, n = mContentStart; i < n; ++i) {
                prepareSlotContent(i);
            }
            for (int i = mContentEnd; i < contentEnd; ++i) {
                prepareSlotContent(i);
            }
        }

        mContentStart = contentStart;
        mContentEnd = contentEnd;
    }

    public void setActiveWindow(int start, int end) {
        Utils.assertTrue(
                start <= end && end - start <= mData.length && end <= mSize,
                "start = %s, end = %s, length = %s, size = %s",
                start, end, mData.length, mSize);

        AlbumSetItem data[] = mData;

        mActiveStart = start;
        mActiveEnd = end;

        // If no data is visible, keep the cache content
        if (start == end) return;

        int contentStart = Utils.clamp((start + end) / 2 - data.length / 2,
                0, Math.max(0, mSize - data.length));
        int contentEnd = Math.min(contentStart + data.length, mSize);
        setContentWindow(contentStart, contentEnd);
        if (mIsActive) updateAllImageRequests();
    }

    // We would like to request non active slots in the following order:
    // Order:    8 6 4 2                   1 3 5 7
    //         |---------|---------------|---------|
    //                   |<-  active  ->|
    //         |<-------- cached range ----------->|
    private void requestNonactiveImages() {
        int range = Math.max(
                mContentEnd - mActiveEnd, mActiveStart - mContentStart);
        for (int i = 0 ;i < range; ++i) {
            requestImagesInSlot(mActiveEnd + i);
            requestImagesInSlot(mActiveStart - 1 - i);
        }
    }

    private void cancelNonactiveImages() {
        int range = Math.max(
                mContentEnd - mActiveEnd, mActiveStart - mContentStart);
        for (int i = 0 ;i < range; ++i) {
            cancelImagesInSlot(mActiveEnd + i);
            cancelImagesInSlot(mActiveStart - 1 - i);
        }
    }

    private void requestImagesInSlot(int slotIndex) {
        if (slotIndex < mContentStart || slotIndex >= mContentEnd) return;
        AlbumSetItem items = mData[slotIndex % mData.length];
        for (DisplayItem item : items.covers) {
            ((GalleryDisplayItem) item).requestImage();
        }
    }

    private void cancelImagesInSlot(int slotIndex) {
        if (slotIndex < mContentStart || slotIndex >= mContentEnd) return;
        AlbumSetItem items = mData[slotIndex % mData.length];
        for (DisplayItem item : items.covers) {
            ((GalleryDisplayItem) item).cancelImageRequest();
        }
    }

    private void freeSlotContent(int slotIndex) {
        AlbumSetItem data[] = mData;
        int index = slotIndex % data.length;
        AlbumSetItem original = data[index];
        if (original != null) {
            data[index] = null;
            for (DisplayItem item : original.covers) {
                ((GalleryDisplayItem) item).recycle();
            }
        }
    }

    private long getMediaSetDataVersion(MediaSet set) {
        return set == null
                ? MediaSet.INVALID_DATA_VERSION
                : set.getDataVersion();
    }

    private void prepareSlotContent(int slotIndex) {
        MediaSet set = mSource.getMediaSet(slotIndex);

        MyAlbumSetItem item = new MyAlbumSetItem();
        MediaItem[] coverItems = mSource.getCoverItems(slotIndex);
        item.covers = new GalleryDisplayItem[coverItems.length];
        item.sourceType = identifySourceType(set);
        item.cacheFlag = identifyCacheFlag(set);
        item.cacheStatus = identifyCacheStatus(set);
        item.setPath = set == null ? null : set.getPath();

        for (int i = 0; i < coverItems.length; ++i) {
            item.covers[i] = new GalleryDisplayItem(slotIndex, i, coverItems[i]);
        }
        item.labelItem = new LabelDisplayItem(slotIndex);
        item.setDataVersion = getMediaSetDataVersion(set);
        mData[slotIndex % mData.length] = item;
    }

    private boolean isCoverItemsChanged(int slotIndex) {
        AlbumSetItem original = mData[slotIndex % mData.length];
        if (original == null) return true;
        MediaItem[] coverItems = mSource.getCoverItems(slotIndex);

        if (original.covers.length != coverItems.length) return true;
        for (int i = 0, n = coverItems.length; i < n; ++i) {
            GalleryDisplayItem g = (GalleryDisplayItem) original.covers[i];
            if (g.mDataVersion != coverItems[i].getDataVersion()) return true;
        }
        return false;
    }

    private void updateSlotContent(final int slotIndex) {

        MyAlbumSetItem data[] = mData;
        int pos = slotIndex % data.length;
        MyAlbumSetItem original = data[pos];

        if (!isCoverItemsChanged(slotIndex)) {
            MediaSet set = mSource.getMediaSet(slotIndex);
            original.sourceType = identifySourceType(set);
            original.cacheFlag = identifyCacheFlag(set);
            original.cacheStatus = identifyCacheStatus(set);
            original.setPath = set == null ? null : set.getPath();
            ((LabelDisplayItem) original.labelItem).updateContent();
            if (mListener != null) mListener.onContentInvalidated();
            return;
        }

        prepareSlotContent(slotIndex);
        AlbumSetItem update = data[pos];

        if (mListener != null && isActiveSlot(slotIndex)) {
            mListener.onWindowContentChanged(slotIndex, original, update);
        }
        if (original != null) {
            for (DisplayItem item : original.covers) {
                ((GalleryDisplayItem) item).recycle();
            }
        }
    }

    private void notifySlotChanged(int slotIndex) {
        // If the updated content is not cached, ignore it
        if (slotIndex < mContentStart || slotIndex >= mContentEnd) {
            Log.w(TAG, String.format(
                    "invalid update: %s is outside (%s, %s)",
                    slotIndex, mContentStart, mContentEnd) );
            return;
        }
        updateSlotContent(slotIndex);
        boolean isActiveSlot = isActiveSlot(slotIndex);
        if (mActiveRequestCount == 0 || isActiveSlot) {
            for (DisplayItem item : mData[slotIndex % mData.length].covers) {
                GalleryDisplayItem galleryItem = (GalleryDisplayItem) item;
                galleryItem.requestImage();
                if (isActiveSlot && galleryItem.isRequestInProgress()) {
                    ++mActiveRequestCount;
                }
            }
        }
    }

    private void updateAllImageRequests() {
        mActiveRequestCount = 0;
        for (int i = mActiveStart, n = mActiveEnd; i < n; ++i) {
            for (DisplayItem item : mData[i % mData.length].covers) {
                GalleryDisplayItem coverItem = (GalleryDisplayItem) item;
                coverItem.requestImage();
                if (coverItem.isRequestInProgress()) ++mActiveRequestCount;
            }
        }
        if (mActiveRequestCount == 0) {
            requestNonactiveImages();
        } else {
            cancelNonactiveImages();
        }
    }

    private class GalleryDisplayItem extends AbstractDisplayItem
            implements FutureListener<Bitmap> {
        private Future<Bitmap> mFuture;
        private final int mSlotIndex;
        private final int mCoverIndex;
        private final int mMediaType;
        private Texture mContent;
        private final long mDataVersion;
        private boolean mIsPanorama;
        private boolean mWaitLoadingDisplayed;

        public GalleryDisplayItem(int slotIndex, int coverIndex, MediaItem item) {
            super(item);
            mSlotIndex = slotIndex;
            mCoverIndex = coverIndex;
            mMediaType = item.getMediaType();
            mDataVersion = item.getDataVersion();
            mIsPanorama = GalleryUtils.isPanorama(item);
            updateContent(mWaitLoadingTexture);
        }

        @Override
        protected void onBitmapAvailable(Bitmap bitmap) {
            if (isActiveSlot(mSlotIndex)) {
                --mActiveRequestCount;
                if (mActiveRequestCount == 0) requestNonactiveImages();
            }
            if (bitmap != null) {
                BitmapTexture texture = new BitmapTexture(bitmap, true);
                texture.setThrottled(true);
                if (mWaitLoadingDisplayed) {
                    updateContent(new FadeInTexture(PLACEHOLDER_COLOR, texture));
                } else {
                    updateContent(texture);
                }
                if (mListener != null) mListener.onContentInvalidated();
            }
        }

        private void updateContent(Texture content) {
            mContent = content;
        }

        @Override
        public int render(GLCanvas canvas, int pass) {
            // Fit the content into the box
            int width = mContent.getWidth();
            int height = mContent.getHeight();

            float scalex = mBoxWidth / (float) width;
            float scaley = mBoxHeight / (float) height;
            float scale = Math.min(scalex, scaley);

            width = (int) Math.floor(width * scale);
            height = (int) Math.floor(height * scale);

            // Now draw it
            int sourceType = SelectionDrawer.DATASOURCE_TYPE_NOT_CATEGORIZED;
            int cacheFlag = MediaSet.CACHE_FLAG_NO;
            int cacheStatus = MediaSet.CACHE_STATUS_NOT_CACHED;
            MyAlbumSetItem set = mData[mSlotIndex % mData.length];
            Path path = set.setPath;
            if (mCoverIndex == 0) {
                sourceType = set.sourceType;
                cacheFlag = set.cacheFlag;
                cacheStatus = set.cacheStatus;
            }

            mSelectionDrawer.draw(canvas, mContent, width, height,
                    getRotation(), path, sourceType, mMediaType,
                    mIsPanorama, mLabelSpec.labelBackgroundHeight,
                    cacheFlag == MediaSet.CACHE_FLAG_FULL,
                    (cacheFlag == MediaSet.CACHE_FLAG_FULL)
                    && (cacheStatus != MediaSet.CACHE_STATUS_CACHED_FULL));

            if (mContent == mWaitLoadingTexture) {
                mWaitLoadingDisplayed = true;
            }

            if ((mContent instanceof FadeInTexture) &&
                    ((FadeInTexture) mContent).isAnimating()) {
                return RENDER_MORE_FRAME;
            } else {
                return 0;
            }
        }

        @Override
        public void startLoadBitmap() {
            mFuture = mThreadPool.submit(mMediaItem.requestImage(
                    MediaItem.TYPE_MICROTHUMBNAIL), this);
        }

        @Override
        public void cancelLoadBitmap() {
            mFuture.cancel();
        }

        @Override
        public void onFutureDone(Future<Bitmap> future) {
            mHandler.sendMessage(mHandler.obtainMessage(MSG_LOAD_BITMAP_DONE, this));
        }

        private void onLoadBitmapDone() {
            Future<Bitmap> future = mFuture;
            mFuture = null;
            updateImage(future.get(), future.isCancelled());
        }

        @Override
        public String toString() {
            return String.format("GalleryDisplayItem(%s, %s)", mSlotIndex, mCoverIndex);
        }
    }

    private static int identifySourceType(MediaSet set) {
        if (set == null) {
            return SelectionDrawer.DATASOURCE_TYPE_NOT_CATEGORIZED;
        }

        Path path = set.getPath();
        if (MediaSetUtils.isCameraSource(path)) {
            return SelectionDrawer.DATASOURCE_TYPE_CAMERA;
        }

        int type = SelectionDrawer.DATASOURCE_TYPE_NOT_CATEGORIZED;
        String prefix = path.getPrefix();

        if (prefix.equals("picasa")) {
            type = SelectionDrawer.DATASOURCE_TYPE_PICASA;
        } else if (prefix.equals("local") || prefix.equals("merge")) {
            type = SelectionDrawer.DATASOURCE_TYPE_LOCAL;
        } else if (prefix.equals("mtp")) {
            type = SelectionDrawer.DATASOURCE_TYPE_MTP;
        }

        return type;
    }

    private static int identifyCacheFlag(MediaSet set) {
        if (set == null || (set.getSupportedOperations()
                & MediaSet.SUPPORT_CACHE) == 0) {
            return MediaSet.CACHE_FLAG_NO;
        }

        return set.getCacheFlag();
    }

    private static int identifyCacheStatus(MediaSet set) {
        if (set == null || (set.getSupportedOperations()
                & MediaSet.SUPPORT_CACHE) == 0) {
            return MediaSet.CACHE_STATUS_NOT_CACHED;
        }

        return set.getCacheStatus();
    }

    private class LabelDisplayItem extends DisplayItem {
        private static final int FONT_COLOR_TITLE = Color.WHITE;
        private static final int FONT_COLOR_COUNT = 0x80FFFFFF;  // 50% white

        private StringTexture mTextureTitle;
        private StringTexture mTextureCount;
        private String mTitle;
        private String mCount;
        private int mLastWidth;
        private final int mSlotIndex;
        private boolean mHasIcon;

        public LabelDisplayItem(int slotIndex) {
            mSlotIndex = slotIndex;
        }

        public boolean updateContent() {
            String title = mLoadingLabel;
            String count = "";
            MediaSet set = mSource.getMediaSet(mSlotIndex);
            if (set != null) {
                title = Utils.ensureNotNull(set.getName());
                count = "" + set.getTotalMediaItemCount();
            }
            if (Utils.equals(title, mTitle)
                    && Utils.equals(count, mCount)
                    && Utils.equals(mBoxWidth, mLastWidth)) {
                    return false;
            }
            mTitle = title;
            mCount = count;
            mLastWidth = mBoxWidth;
            mHasIcon = (identifySourceType(set) !=
                    SelectionDrawer.DATASOURCE_TYPE_NOT_CATEGORIZED);

            AlbumSetView.LabelSpec s = mLabelSpec;
            mTextureTitle = StringTexture.newInstance(
                    title, s.titleFontSize, FONT_COLOR_TITLE,
                    mBoxWidth - s.leftMargin, false);
            mTextureCount = StringTexture.newInstance(
                    count, s.countFontSize, FONT_COLOR_COUNT,
                    mBoxWidth - s.leftMargin, true);

            return true;
        }

        @Override
        public int render(GLCanvas canvas, int pass) {
            if (mBoxWidth != mLastWidth) {
                updateContent();
            }

            AlbumSetView.LabelSpec s = mLabelSpec;
            int x = -mBoxWidth / 2;
            int y = (mBoxHeight + 1) / 2 - s.labelBackgroundHeight;
            y += s.titleOffset;
            mTextureTitle.draw(canvas, x + s.leftMargin, y);
            y += s.titleFontSize + s.countOffset;
            x += mHasIcon ? s.iconSize : s.leftMargin;
            mTextureCount.draw(canvas, x, y);
            return 0;
        }

        @Override
        public long getIdentity() {
            return System.identityHashCode(this);
        }
    }

    public void onSizeChanged(int size) {
        if (mSize != size) {
            mSize = size;
            if (mListener != null && mIsActive) mListener.onSizeChanged(mSize);
        }
    }

    public void onWindowContentChanged(int index) {
        if (!mIsActive) {
            // paused, ignore slot changed event
            return;
        }
        notifySlotChanged(index);
    }

    public void pause() {
        mIsActive = false;
        for (int i = mContentStart, n = mContentEnd; i < n; ++i) {
            freeSlotContent(i);
        }
    }

    public void resume() {
        mIsActive = true;
        for (int i = mContentStart, n = mContentEnd; i < n; ++i) {
            prepareSlotContent(i);
        }
        updateAllImageRequests();
    }
}