2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.gallery3d.ui;
19 import android.graphics.Bitmap;
20 import android.graphics.Point;
21 import android.graphics.Rect;
22 import android.graphics.RectF;
23 import android.util.FloatMath;
25 import com.android.gallery3d.app.GalleryContext;
26 import com.android.gallery3d.common.ApiHelper;
27 import com.android.gallery3d.common.LongSparseArray;
28 import com.android.gallery3d.common.Utils;
29 import com.android.gallery3d.data.BitmapPool;
30 import com.android.gallery3d.data.DecodeUtils;
31 import com.android.gallery3d.util.Future;
32 import com.android.gallery3d.util.GalleryUtils;
33 import com.android.gallery3d.util.ThreadPool;
34 import com.android.gallery3d.util.ThreadPool.CancelListener;
35 import com.android.gallery3d.util.ThreadPool.JobContext;
37 import java.util.concurrent.atomic.AtomicBoolean;
39 public class TileImageView extends GLView {
40 public static final int SIZE_UNKNOWN = -1;
42 @SuppressWarnings("unused")
43 private static final String TAG = "TileImageView";
45 // TILE_SIZE must be 2^N - 2. We put one pixel border in each side of the
46 // texture to avoid seams between tiles.
47 private static int TILE_SIZE;
48 private static final int TILE_BORDER = 1;
49 private static int BITMAP_SIZE;
50 private static final int UPLOAD_LIMIT = 1;
52 private static BitmapPool sTilePool;
55 * This is the tile state in the CPU side.
57 * ACTIVATED (initial state)
58 * --> IN_QUEUE - by queueForDecode()
59 * --> RECYCLED - by recycleTile()
60 * IN_QUEUE --> DECODING - by decodeTile()
61 * --> RECYCLED - by recycleTile)
62 * DECODING --> RECYCLING - by recycleTile()
63 * --> DECODED - by decodeTile()
64 * --> DECODE_FAIL - by decodeTile()
65 * RECYCLING --> RECYCLED - by decodeTile()
66 * DECODED --> ACTIVATED - (after the decoded bitmap is uploaded)
67 * DECODED --> RECYCLED - by recycleTile()
68 * DECODE_FAIL -> RECYCLED - by recycleTile()
69 * RECYCLED --> ACTIVATED - by obtainTile()
71 private static final int STATE_ACTIVATED = 0x01;
72 private static final int STATE_IN_QUEUE = 0x02;
73 private static final int STATE_DECODING = 0x04;
74 private static final int STATE_DECODED = 0x08;
75 private static final int STATE_DECODE_FAIL = 0x10;
76 private static final int STATE_RECYCLING = 0x20;
77 private static final int STATE_RECYCLED = 0x40;
80 private ScreenNail mScreenNail;
81 protected int mLevelCount; // cache the value of mScaledBitmaps.length
83 // The mLevel variable indicates which level of bitmap we should use.
84 // Level 0 means the original full-sized bitmap, and a larger value means
85 // a smaller scaled bitmap (The width and height of each scaled bitmap is
86 // half size of the previous one). If the value is in [0, mLevelCount), we
87 // use the bitmap in mScaledBitmaps[mLevel] for display, otherwise the value
88 // is mLevelCount, and that means we use mScreenNail for display.
89 private int mLevel = 0;
91 // The offsets of the (left, top) of the upper-left tile to the (left, top)
96 private int mUploadQuota;
97 private boolean mRenderComplete;
99 private final RectF mSourceRect = new RectF();
100 private final RectF mTargetRect = new RectF();
102 private final LongSparseArray<Tile> mActiveTiles = new LongSparseArray<Tile>();
104 // The following three queue is guarded by TileImageView.this
105 private final TileQueue mRecycledQueue = new TileQueue();
106 private final TileQueue mUploadQueue = new TileQueue();
107 private final TileQueue mDecodeQueue = new TileQueue();
109 // The width and height of the full-sized bitmap
110 protected int mImageWidth = SIZE_UNKNOWN;
111 protected int mImageHeight = SIZE_UNKNOWN;
113 protected int mCenterX;
114 protected int mCenterY;
115 protected float mScale;
116 protected int mRotation;
118 // Temp variables to avoid memory allocation
119 private final Rect mTileRange = new Rect();
120 private final Rect mActiveRange[] = {new Rect(), new Rect()};
122 private final TileUploader mTileUploader = new TileUploader();
123 private boolean mIsTextureFreed;
124 private Future<Void> mTileDecoder;
125 private final ThreadPool mThreadPool;
126 private boolean mBackgroundTileUploaded;
128 public static interface Model {
129 public int getLevelCount();
130 public ScreenNail getScreenNail();
131 public int getImageWidth();
132 public int getImageHeight();
134 // The tile returned by this method can be specified this way: Assuming
135 // the image size is (width, height), first take the intersection of (0,
136 // 0) - (width, height) and (x, y) - (x + tileSize, y + tileSize). Then
137 // extend this intersection region by borderSize pixels on each side. If
138 // in extending the region, we found some part of the region are outside
139 // the image, those pixels are filled with black.
141 // If level > 0, it does the same operation on a down-scaled version of
142 // the original image (down-scaled by a factor of 2^level), but (x, y)
143 // still refers to the coordinate on the original image.
145 // The method would be called in another thread.
146 public Bitmap getTile(int level, int x, int y, int tileSize,
147 int borderSize, BitmapPool pool);
150 public TileImageView(GalleryContext context) {
151 mThreadPool = context.getThreadPool();
152 mTileDecoder = mThreadPool.submit(new TileDecoder());
153 if (TILE_SIZE == 0) {
154 if (GalleryUtils.isHighResolution(context.getAndroidContext())) {
159 BITMAP_SIZE = TILE_SIZE + TILE_BORDER * 2;
161 ApiHelper.HAS_REUSING_BITMAP_IN_BITMAP_REGION_DECODER
162 ? new BitmapPool(BITMAP_SIZE, BITMAP_SIZE, 128)
167 public void setModel(Model model) {
169 if (model != null) notifyModelInvalidated();
172 public void setScreenNail(ScreenNail s) {
176 public void notifyModelInvalidated() {
178 if (mModel == null) {
184 setScreenNail(mModel.getScreenNail());
185 mImageWidth = mModel.getImageWidth();
186 mImageHeight = mModel.getImageHeight();
187 mLevelCount = mModel.getLevelCount();
189 layoutTiles(mCenterX, mCenterY, mScale, mRotation);
194 protected void onLayout(
195 boolean changeSize, int left, int top, int right, int bottom) {
196 super.onLayout(changeSize, left, top, right, bottom);
197 if (changeSize) layoutTiles(mCenterX, mCenterY, mScale, mRotation);
200 // Prepare the tiles we want to use for display.
202 // 1. Decide the tile level we want to use for display.
203 // 2. Decide the tile levels we want to keep as texture (in addition to
204 // the one we use for display).
205 // 3. Recycle unused tiles.
206 // 4. Activate the tiles we want.
207 private void layoutTiles(int centerX, int centerY, float scale, int rotation) {
208 // The width and height of this view.
209 int width = getWidth();
210 int height = getHeight();
212 // The tile levels we want to keep as texture is in the range
213 // [fromLevel, endLevel).
217 // We want to use a texture larger than or equal to the display size.
218 mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount);
220 // We want to keep one more tile level as texture in addition to what
221 // we use for display. So it can be faster when the scale moves to the
222 // next level. We choose a level closer to the current scale.
223 if (mLevel != mLevelCount) {
224 Rect range = mTileRange;
225 getRange(range, centerX, centerY, mLevel, scale, rotation);
226 mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale);
227 mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale);
228 fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel;
230 // Activate the tiles of the smallest two levels.
231 fromLevel = mLevel - 2;
232 mOffsetX = Math.round(width / 2f - centerX * scale);
233 mOffsetY = Math.round(height / 2f - centerY * scale);
236 fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2));
237 endLevel = Math.min(fromLevel + 2, mLevelCount);
239 Rect range[] = mActiveRange;
240 for (int i = fromLevel; i < endLevel; ++i) {
241 getRange(range[i - fromLevel], centerX, centerY, i, rotation);
244 // If rotation is transient, don't update the tile.
245 if (rotation % 90 != 0) return;
247 synchronized (this) {
248 mDecodeQueue.clean();
249 mUploadQueue.clean();
250 mBackgroundTileUploaded = false;
252 // Recycle unused tiles: if the level of the active tile is outside the
253 // range [fromLevel, endLevel) or not in the visible range.
254 int n = mActiveTiles.size();
255 for (int i = 0; i < n; i++) {
256 Tile tile = mActiveTiles.valueAt(i);
257 int level = tile.mTileLevel;
258 if (level < fromLevel || level >= endLevel
259 || !range[level - fromLevel].contains(tile.mX, tile.mY)) {
260 mActiveTiles.removeAt(i);
268 for (int i = fromLevel; i < endLevel; ++i) {
269 int size = TILE_SIZE << i;
270 Rect r = range[i - fromLevel];
271 for (int y = r.top, bottom = r.bottom; y < bottom; y += size) {
272 for (int x = r.left, right = r.right; x < right; x += size) {
273 activateTile(x, y, i);
280 protected synchronized void invalidateTiles() {
281 mDecodeQueue.clean();
282 mUploadQueue.clean();
284 // TODO disable decoder
285 int n = mActiveTiles.size();
286 for (int i = 0; i < n; i++) {
287 Tile tile = mActiveTiles.valueAt(i);
290 mActiveTiles.clear();
293 private void getRange(Rect out, int cX, int cY, int level, int rotation) {
294 getRange(out, cX, cY, level, 1f / (1 << (level + 1)), rotation);
297 // If the bitmap is scaled by the given factor "scale", return the
298 // rectangle containing visible range. The left-top coordinate returned is
299 // aligned to the tile boundary.
301 // (cX, cY) is the point on the original bitmap which will be put in the
302 // center of the ImageViewer.
303 private void getRange(Rect out,
304 int cX, int cY, int level, float scale, int rotation) {
306 double radians = Math.toRadians(-rotation);
307 double w = getWidth();
308 double h = getHeight();
310 double cos = Math.cos(radians);
311 double sin = Math.sin(radians);
312 int width = (int) Math.ceil(Math.max(
313 Math.abs(cos * w - sin * h), Math.abs(cos * w + sin * h)));
314 int height = (int) Math.ceil(Math.max(
315 Math.abs(sin * w + cos * h), Math.abs(sin * w - cos * h)));
317 int left = (int) FloatMath.floor(cX - width / (2f * scale));
318 int top = (int) FloatMath.floor(cY - height / (2f * scale));
319 int right = (int) FloatMath.ceil(left + width / scale);
320 int bottom = (int) FloatMath.ceil(top + height / scale);
322 // align the rectangle to tile boundary
323 int size = TILE_SIZE << level;
324 left = Math.max(0, size * (left / size));
325 top = Math.max(0, size * (top / size));
326 right = Math.min(mImageWidth, right);
327 bottom = Math.min(mImageHeight, bottom);
329 out.set(left, top, right, bottom);
332 // Calculate where the center of the image is, in the view coordinates.
333 public void getImageCenter(Point center) {
334 // The width and height of this view.
335 int viewW = getWidth();
336 int viewH = getHeight();
338 // The distance between the center of the view to the center of the
339 // bitmap, in bitmap units. (mCenterX and mCenterY are the bitmap
340 // coordinates correspond to the center of view)
342 if (mRotation % 180 == 0) {
343 distW = mImageWidth / 2 - mCenterX;
344 distH = mImageHeight / 2 - mCenterY;
346 distW = mImageHeight / 2 - mCenterY;
347 distH = mImageWidth / 2 - mCenterX;
350 // Convert to view coordinates. mScale translates from bitmap units to
352 center.x = Math.round(viewW / 2f + distW * mScale);
353 center.y = Math.round(viewH / 2f + distH * mScale);
356 public boolean setPosition(int centerX, int centerY, float scale, int rotation) {
357 if (mCenterX == centerX && mCenterY == centerY
358 && mScale == scale && mRotation == rotation) return false;
362 mRotation = rotation;
363 layoutTiles(centerX, centerY, scale, rotation);
368 public void freeTextures() {
369 mIsTextureFreed = true;
371 if (mTileDecoder != null) {
372 mTileDecoder.cancel();
377 int n = mActiveTiles.size();
378 for (int i = 0; i < n; i++) {
379 Tile texture = mActiveTiles.valueAt(i);
382 mActiveTiles.clear();
383 mTileRange.set(0, 0, 0, 0);
385 synchronized (this) {
386 mUploadQueue.clean();
387 mDecodeQueue.clean();
388 Tile tile = mRecycledQueue.pop();
389 while (tile != null) {
391 tile = mRecycledQueue.pop();
395 if (sTilePool != null) sTilePool.clear();
398 public void prepareTextures() {
399 if (mTileDecoder == null) {
400 mTileDecoder = mThreadPool.submit(new TileDecoder());
402 if (mIsTextureFreed) {
403 layoutTiles(mCenterX, mCenterY, mScale, mRotation);
404 mIsTextureFreed = false;
405 setScreenNail(mModel == null ? null : mModel.getScreenNail());
410 protected void render(GLCanvas canvas) {
411 mUploadQuota = UPLOAD_LIMIT;
412 mRenderComplete = true;
415 int rotation = mRotation;
417 if (rotation != 0) flags |= GLCanvas.SAVE_FLAG_MATRIX;
422 int centerX = getWidth() / 2, centerY = getHeight() / 2;
423 canvas.translate(centerX, centerY);
424 canvas.rotate(rotation, 0, 0, 1);
425 canvas.translate(-centerX, -centerY);
429 if (level != mLevelCount && !isScreenNailAnimating()) {
430 if (mScreenNail != null) {
431 mScreenNail.noDraw();
434 int size = (TILE_SIZE << level);
435 float length = size * mScale;
438 for (int ty = r.top, i = 0; ty < r.bottom; ty += size, i++) {
439 float y = mOffsetY + i * length;
440 for (int tx = r.left, j = 0; tx < r.right; tx += size, j++) {
441 float x = mOffsetX + j * length;
442 drawTile(canvas, tx, ty, level, x, y, length);
445 } else if (mScreenNail != null) {
446 mScreenNail.draw(canvas, mOffsetX, mOffsetY,
447 Math.round(mImageWidth * mScale),
448 Math.round(mImageHeight * mScale));
449 if (isScreenNailAnimating()) {
454 if (flags != 0) canvas.restore();
457 if (mRenderComplete) {
458 if (!mBackgroundTileUploaded) uploadBackgroundTiles(canvas);
464 private boolean isScreenNailAnimating() {
465 return (mScreenNail instanceof BitmapScreenNail)
466 && ((BitmapScreenNail) mScreenNail).isAnimating();
469 private void uploadBackgroundTiles(GLCanvas canvas) {
470 mBackgroundTileUploaded = true;
471 int n = mActiveTiles.size();
472 for (int i = 0; i < n; i++) {
473 Tile tile = mActiveTiles.valueAt(i);
474 if (!tile.isContentValid()) queueForDecode(tile);
478 void queueForUpload(Tile tile) {
479 synchronized (this) {
480 mUploadQueue.push(tile);
482 if (mTileUploader.mActive.compareAndSet(false, true)) {
483 getGLRoot().addOnGLIdleListener(mTileUploader);
487 synchronized void queueForDecode(Tile tile) {
488 if (tile.mTileState == STATE_ACTIVATED) {
489 tile.mTileState = STATE_IN_QUEUE;
490 if (mDecodeQueue.push(tile)) notifyAll();
494 boolean decodeTile(Tile tile) {
495 synchronized (this) {
496 if (tile.mTileState != STATE_IN_QUEUE) return false;
497 tile.mTileState = STATE_DECODING;
499 boolean decodeComplete = tile.decode();
500 synchronized (this) {
501 if (tile.mTileState == STATE_RECYCLING) {
502 tile.mTileState = STATE_RECYCLED;
503 if (tile.mDecodedTile != null) {
504 if (sTilePool != null) sTilePool.recycle(tile.mDecodedTile);
505 tile.mDecodedTile = null;
507 mRecycledQueue.push(tile);
510 tile.mTileState = decodeComplete ? STATE_DECODED : STATE_DECODE_FAIL;
511 return decodeComplete;
515 private synchronized Tile obtainTile(int x, int y, int level) {
516 Tile tile = mRecycledQueue.pop();
518 tile.mTileState = STATE_ACTIVATED;
519 tile.update(x, y, level);
522 return new Tile(x, y, level);
525 synchronized void recycleTile(Tile tile) {
526 if (tile.mTileState == STATE_DECODING) {
527 tile.mTileState = STATE_RECYCLING;
530 tile.mTileState = STATE_RECYCLED;
531 if (tile.mDecodedTile != null) {
532 if (sTilePool != null) sTilePool.recycle(tile.mDecodedTile);
533 tile.mDecodedTile = null;
535 mRecycledQueue.push(tile);
538 private void activateTile(int x, int y, int level) {
539 long key = makeTileKey(x, y, level);
540 Tile tile = mActiveTiles.get(key);
542 if (tile.mTileState == STATE_IN_QUEUE) {
543 tile.mTileState = STATE_ACTIVATED;
547 tile = obtainTile(x, y, level);
548 mActiveTiles.put(key, tile);
551 private Tile getTile(int x, int y, int level) {
552 return mActiveTiles.get(makeTileKey(x, y, level));
555 private static long makeTileKey(int x, int y, int level) {
557 result = (result << 16) | y;
558 result = (result << 16) | level;
562 private class TileUploader implements GLRoot.OnGLIdleListener {
563 AtomicBoolean mActive = new AtomicBoolean(false);
566 public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
567 // Skips uploading if there is a pending rendering request.
568 // Returns true to keep uploading in next rendering loop.
569 if (renderRequested) return true;
570 int quota = UPLOAD_LIMIT;
573 synchronized (TileImageView.this) {
574 tile = mUploadQueue.pop();
576 if (tile == null) break;
577 if (!tile.isContentValid()) {
578 Utils.assertTrue(tile.mTileState == STATE_DECODED);
579 tile.updateContent(canvas);
583 if (tile == null) mActive.set(false);
588 // Draw the tile to a square at canvas that locates at (x, y) and
589 // has a side length of length.
590 public void drawTile(GLCanvas canvas,
591 int tx, int ty, int level, float x, float y, float length) {
592 RectF source = mSourceRect;
593 RectF target = mTargetRect;
594 target.set(x, y, x + length, y + length);
595 source.set(0, 0, TILE_SIZE, TILE_SIZE);
597 Tile tile = getTile(tx, ty, level);
599 if (!tile.isContentValid()) {
600 if (tile.mTileState == STATE_DECODED) {
601 if (mUploadQuota > 0) {
603 tile.updateContent(canvas);
605 mRenderComplete = false;
607 } else if (tile.mTileState != STATE_DECODE_FAIL){
608 mRenderComplete = false;
609 queueForDecode(tile);
612 if (drawTile(tile, canvas, source, target)) return;
614 if (mScreenNail != null) {
615 int size = TILE_SIZE << level;
616 float scaleX = (float) mScreenNail.getWidth() / mImageWidth;
617 float scaleY = (float) mScreenNail.getHeight() / mImageHeight;
618 source.set(tx * scaleX, ty * scaleY, (tx + size) * scaleX,
619 (ty + size) * scaleY);
620 mScreenNail.draw(canvas, source, target);
624 // TODO: avoid drawing the unused part of the textures.
625 static boolean drawTile(
626 Tile tile, GLCanvas canvas, RectF source, RectF target) {
628 if (tile.isContentValid()) {
629 // offset source rectangle for the texture border.
630 source.offset(TILE_BORDER, TILE_BORDER);
631 canvas.drawTexture(tile, source, target);
635 // Parent can be divided to four quads and tile is one of the four.
636 Tile parent = tile.getParentTile();
637 if (parent == null) return false;
638 if (tile.mX == parent.mX) {
642 source.left = (TILE_SIZE + source.left) / 2f;
643 source.right = (TILE_SIZE + source.right) / 2f;
645 if (tile.mY == parent.mY) {
649 source.top = (TILE_SIZE + source.top) / 2f;
650 source.bottom = (TILE_SIZE + source.bottom) / 2f;
656 private class Tile extends UploadedTexture {
659 public int mTileLevel;
661 public Bitmap mDecodedTile;
662 public volatile int mTileState = STATE_ACTIVATED;
664 public Tile(int x, int y, int level) {
671 protected void onFreeBitmap(Bitmap bitmap) {
672 if (sTilePool != null) sTilePool.recycle(bitmap);
676 // Get a tile from the original image. The tile is down-scaled
677 // by (1 << mTilelevel) from a region in the original image.
679 mDecodedTile = DecodeUtils.ensureGLCompatibleBitmap(mModel.getTile(
680 mTileLevel, mX, mY, TILE_SIZE, TILE_BORDER, sTilePool));
681 } catch (Throwable t) {
682 Log.w(TAG, "fail to decode tile", t);
684 return mDecodedTile != null;
688 protected Bitmap onGetBitmap() {
689 Utils.assertTrue(mTileState == STATE_DECODED);
691 // We need to override the width and height, so that we won't
692 // draw beyond the boundaries.
693 int rightEdge = ((mImageWidth - mX) >> mTileLevel) + TILE_BORDER;
694 int bottomEdge = ((mImageHeight - mY) >> mTileLevel) + TILE_BORDER;
695 setSize(Math.min(BITMAP_SIZE, rightEdge), Math.min(BITMAP_SIZE, bottomEdge));
697 Bitmap bitmap = mDecodedTile;
699 mTileState = STATE_ACTIVATED;
703 // We override getTextureWidth() and getTextureHeight() here, so the
704 // texture can be re-used for different tiles regardless of the actual
705 // size of the tile (which may be small because it is a tile at the
708 public int getTextureWidth() {
709 return TILE_SIZE + TILE_BORDER * 2;
713 public int getTextureHeight() {
714 return TILE_SIZE + TILE_BORDER * 2;
717 public void update(int x, int y, int level) {
724 public Tile getParentTile() {
725 if (mTileLevel + 1 == mLevelCount) return null;
726 int size = TILE_SIZE << (mTileLevel + 1);
727 int x = size * (mX / size);
728 int y = size * (mY / size);
729 return getTile(x, y, mTileLevel + 1);
733 public String toString() {
734 return String.format("tile(%s, %s, %s / %s)",
735 mX / TILE_SIZE, mY / TILE_SIZE, mLevel, mLevelCount);
739 private static class TileQueue {
744 if (tile != null) mHead = tile.mNext;
748 public boolean push(Tile tile) {
749 boolean wasEmpty = mHead == null;
755 public void clean() {
760 private class TileDecoder implements ThreadPool.Job<Void> {
762 private CancelListener mNotifier = new CancelListener() {
764 public void onCancel() {
765 synchronized (TileImageView.this) {
766 TileImageView.this.notifyAll();
772 public Void run(JobContext jc) {
773 jc.setMode(ThreadPool.MODE_NONE);
774 jc.setCancelListener(mNotifier);
775 while (!jc.isCancelled()) {
777 synchronized(TileImageView.this) {
778 tile = mDecodeQueue.pop();
779 if (tile == null && !jc.isCancelled()) {
780 Utils.waitWithoutInterrupt(TileImageView.this);
783 if (tile == null) continue;
784 if (decodeTile(tile)) queueForUpload(tile);