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.glrenderer.GLCanvas;
32 import com.android.gallery3d.glrenderer.UploadedTexture;
33 import com.android.gallery3d.util.Future;
34 import com.android.gallery3d.util.GalleryUtils;
35 import com.android.gallery3d.util.ThreadPool;
36 import com.android.gallery3d.util.ThreadPool.CancelListener;
37 import com.android.gallery3d.util.ThreadPool.JobContext;
39 import java.util.concurrent.atomic.AtomicBoolean;
41 public class TileImageView extends GLView {
42 public static final int SIZE_UNKNOWN = -1;
44 @SuppressWarnings("unused")
45 private static final String TAG = "TileImageView";
47 // TILE_SIZE must be 2^N - 2. We put one pixel border in each side of the
48 // texture to avoid seams between tiles.
49 private static int TILE_SIZE;
50 private static final int TILE_BORDER = 1;
51 private static int BITMAP_SIZE;
52 private static final int UPLOAD_LIMIT = 1;
54 private static BitmapPool sTilePool;
57 * This is the tile state in the CPU side.
59 * ACTIVATED (initial state)
60 * --> IN_QUEUE - by queueForDecode()
61 * --> RECYCLED - by recycleTile()
62 * IN_QUEUE --> DECODING - by decodeTile()
63 * --> RECYCLED - by recycleTile)
64 * DECODING --> RECYCLING - by recycleTile()
65 * --> DECODED - by decodeTile()
66 * --> DECODE_FAIL - by decodeTile()
67 * RECYCLING --> RECYCLED - by decodeTile()
68 * DECODED --> ACTIVATED - (after the decoded bitmap is uploaded)
69 * DECODED --> RECYCLED - by recycleTile()
70 * DECODE_FAIL -> RECYCLED - by recycleTile()
71 * RECYCLED --> ACTIVATED - by obtainTile()
73 private static final int STATE_ACTIVATED = 0x01;
74 private static final int STATE_IN_QUEUE = 0x02;
75 private static final int STATE_DECODING = 0x04;
76 private static final int STATE_DECODED = 0x08;
77 private static final int STATE_DECODE_FAIL = 0x10;
78 private static final int STATE_RECYCLING = 0x20;
79 private static final int STATE_RECYCLED = 0x40;
82 private ScreenNail mScreenNail;
83 protected int mLevelCount; // cache the value of mScaledBitmaps.length
85 // The mLevel variable indicates which level of bitmap we should use.
86 // Level 0 means the original full-sized bitmap, and a larger value means
87 // a smaller scaled bitmap (The width and height of each scaled bitmap is
88 // half size of the previous one). If the value is in [0, mLevelCount), we
89 // use the bitmap in mScaledBitmaps[mLevel] for display, otherwise the value
90 // is mLevelCount, and that means we use mScreenNail for display.
91 private int mLevel = 0;
93 // The offsets of the (left, top) of the upper-left tile to the (left, top)
98 private int mUploadQuota;
99 private boolean mRenderComplete;
101 private final RectF mSourceRect = new RectF();
102 private final RectF mTargetRect = new RectF();
104 private final LongSparseArray<Tile> mActiveTiles = new LongSparseArray<Tile>();
106 // The following three queue is guarded by TileImageView.this
107 private final TileQueue mRecycledQueue = new TileQueue();
108 private final TileQueue mUploadQueue = new TileQueue();
109 private final TileQueue mDecodeQueue = new TileQueue();
111 // The width and height of the full-sized bitmap
112 protected int mImageWidth = SIZE_UNKNOWN;
113 protected int mImageHeight = SIZE_UNKNOWN;
115 protected int mCenterX;
116 protected int mCenterY;
117 protected float mScale;
118 protected int mRotation;
120 // Temp variables to avoid memory allocation
121 private final Rect mTileRange = new Rect();
122 private final Rect mActiveRange[] = {new Rect(), new Rect()};
124 private final TileUploader mTileUploader = new TileUploader();
125 private boolean mIsTextureFreed;
126 private Future<Void> mTileDecoder;
127 private final ThreadPool mThreadPool;
128 private boolean mBackgroundTileUploaded;
130 public static interface Model {
131 public int getLevelCount();
132 public ScreenNail getScreenNail();
133 public int getImageWidth();
134 public int getImageHeight();
136 // The tile returned by this method can be specified this way: Assuming
137 // the image size is (width, height), first take the intersection of (0,
138 // 0) - (width, height) and (x, y) - (x + tileSize, y + tileSize). Then
139 // extend this intersection region by borderSize pixels on each side. If
140 // in extending the region, we found some part of the region are outside
141 // the image, those pixels are filled with black.
143 // If level > 0, it does the same operation on a down-scaled version of
144 // the original image (down-scaled by a factor of 2^level), but (x, y)
145 // still refers to the coordinate on the original image.
147 // The method would be called in another thread.
148 public Bitmap getTile(int level, int x, int y, int tileSize,
149 int borderSize, BitmapPool pool);
152 public TileImageView(GalleryContext context) {
153 mThreadPool = context.getThreadPool();
154 mTileDecoder = mThreadPool.submit(new TileDecoder());
155 if (TILE_SIZE == 0) {
156 if (GalleryUtils.isHighResolution(context.getAndroidContext())) {
161 BITMAP_SIZE = TILE_SIZE + TILE_BORDER * 2;
163 ApiHelper.HAS_REUSING_BITMAP_IN_BITMAP_REGION_DECODER
164 ? new BitmapPool(BITMAP_SIZE, BITMAP_SIZE, 128)
169 public void setModel(Model model) {
171 if (model != null) notifyModelInvalidated();
174 public void setScreenNail(ScreenNail s) {
178 public void notifyModelInvalidated() {
180 if (mModel == null) {
186 setScreenNail(mModel.getScreenNail());
187 mImageWidth = mModel.getImageWidth();
188 mImageHeight = mModel.getImageHeight();
189 mLevelCount = mModel.getLevelCount();
191 layoutTiles(mCenterX, mCenterY, mScale, mRotation);
196 protected void onLayout(
197 boolean changeSize, int left, int top, int right, int bottom) {
198 super.onLayout(changeSize, left, top, right, bottom);
199 if (changeSize) layoutTiles(mCenterX, mCenterY, mScale, mRotation);
202 // Prepare the tiles we want to use for display.
204 // 1. Decide the tile level we want to use for display.
205 // 2. Decide the tile levels we want to keep as texture (in addition to
206 // the one we use for display).
207 // 3. Recycle unused tiles.
208 // 4. Activate the tiles we want.
209 private void layoutTiles(int centerX, int centerY, float scale, int rotation) {
210 // The width and height of this view.
211 int width = getWidth();
212 int height = getHeight();
214 // The tile levels we want to keep as texture is in the range
215 // [fromLevel, endLevel).
219 // We want to use a texture larger than or equal to the display size.
220 mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount);
222 // We want to keep one more tile level as texture in addition to what
223 // we use for display. So it can be faster when the scale moves to the
224 // next level. We choose a level closer to the current scale.
225 if (mLevel != mLevelCount) {
226 Rect range = mTileRange;
227 getRange(range, centerX, centerY, mLevel, scale, rotation);
228 mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale);
229 mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale);
230 fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel;
232 // Activate the tiles of the smallest two levels.
233 fromLevel = mLevel - 2;
234 mOffsetX = Math.round(width / 2f - centerX * scale);
235 mOffsetY = Math.round(height / 2f - centerY * scale);
238 fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2));
239 endLevel = Math.min(fromLevel + 2, mLevelCount);
241 Rect range[] = mActiveRange;
242 for (int i = fromLevel; i < endLevel; ++i) {
243 getRange(range[i - fromLevel], centerX, centerY, i, rotation);
246 // If rotation is transient, don't update the tile.
247 if (rotation % 90 != 0) return;
249 synchronized (this) {
250 mDecodeQueue.clean();
251 mUploadQueue.clean();
252 mBackgroundTileUploaded = false;
254 // Recycle unused tiles: if the level of the active tile is outside the
255 // range [fromLevel, endLevel) or not in the visible range.
256 int n = mActiveTiles.size();
257 for (int i = 0; i < n; i++) {
258 Tile tile = mActiveTiles.valueAt(i);
259 int level = tile.mTileLevel;
260 if (level < fromLevel || level >= endLevel
261 || !range[level - fromLevel].contains(tile.mX, tile.mY)) {
262 mActiveTiles.removeAt(i);
270 for (int i = fromLevel; i < endLevel; ++i) {
271 int size = TILE_SIZE << i;
272 Rect r = range[i - fromLevel];
273 for (int y = r.top, bottom = r.bottom; y < bottom; y += size) {
274 for (int x = r.left, right = r.right; x < right; x += size) {
275 activateTile(x, y, i);
282 protected synchronized void invalidateTiles() {
283 mDecodeQueue.clean();
284 mUploadQueue.clean();
286 // TODO disable decoder
287 int n = mActiveTiles.size();
288 for (int i = 0; i < n; i++) {
289 Tile tile = mActiveTiles.valueAt(i);
292 mActiveTiles.clear();
295 private void getRange(Rect out, int cX, int cY, int level, int rotation) {
296 getRange(out, cX, cY, level, 1f / (1 << (level + 1)), rotation);
299 // If the bitmap is scaled by the given factor "scale", return the
300 // rectangle containing visible range. The left-top coordinate returned is
301 // aligned to the tile boundary.
303 // (cX, cY) is the point on the original bitmap which will be put in the
304 // center of the ImageViewer.
305 private void getRange(Rect out,
306 int cX, int cY, int level, float scale, int rotation) {
308 double radians = Math.toRadians(-rotation);
309 double w = getWidth();
310 double h = getHeight();
312 double cos = Math.cos(radians);
313 double sin = Math.sin(radians);
314 int width = (int) Math.ceil(Math.max(
315 Math.abs(cos * w - sin * h), Math.abs(cos * w + sin * h)));
316 int height = (int) Math.ceil(Math.max(
317 Math.abs(sin * w + cos * h), Math.abs(sin * w - cos * h)));
319 int left = (int) FloatMath.floor(cX - width / (2f * scale));
320 int top = (int) FloatMath.floor(cY - height / (2f * scale));
321 int right = (int) FloatMath.ceil(left + width / scale);
322 int bottom = (int) FloatMath.ceil(top + height / scale);
324 // align the rectangle to tile boundary
325 int size = TILE_SIZE << level;
326 left = Math.max(0, size * (left / size));
327 top = Math.max(0, size * (top / size));
328 right = Math.min(mImageWidth, right);
329 bottom = Math.min(mImageHeight, bottom);
331 out.set(left, top, right, bottom);
334 // Calculate where the center of the image is, in the view coordinates.
335 public void getImageCenter(Point center) {
336 // The width and height of this view.
337 int viewW = getWidth();
338 int viewH = getHeight();
340 // The distance between the center of the view to the center of the
341 // bitmap, in bitmap units. (mCenterX and mCenterY are the bitmap
342 // coordinates correspond to the center of view)
344 if (mRotation % 180 == 0) {
345 distW = mImageWidth / 2 - mCenterX;
346 distH = mImageHeight / 2 - mCenterY;
348 distW = mImageHeight / 2 - mCenterY;
349 distH = mImageWidth / 2 - mCenterX;
352 // Convert to view coordinates. mScale translates from bitmap units to
354 center.x = Math.round(viewW / 2f + distW * mScale);
355 center.y = Math.round(viewH / 2f + distH * mScale);
358 public boolean setPosition(int centerX, int centerY, float scale, int rotation) {
359 if (mCenterX == centerX && mCenterY == centerY
360 && mScale == scale && mRotation == rotation) return false;
364 mRotation = rotation;
365 layoutTiles(centerX, centerY, scale, rotation);
370 public void freeTextures() {
371 mIsTextureFreed = true;
373 if (mTileDecoder != null) {
374 mTileDecoder.cancel();
379 int n = mActiveTiles.size();
380 for (int i = 0; i < n; i++) {
381 Tile texture = mActiveTiles.valueAt(i);
384 mActiveTiles.clear();
385 mTileRange.set(0, 0, 0, 0);
387 synchronized (this) {
388 mUploadQueue.clean();
389 mDecodeQueue.clean();
390 Tile tile = mRecycledQueue.pop();
391 while (tile != null) {
393 tile = mRecycledQueue.pop();
397 if (sTilePool != null) sTilePool.clear();
400 public void prepareTextures() {
401 if (mTileDecoder == null) {
402 mTileDecoder = mThreadPool.submit(new TileDecoder());
404 if (mIsTextureFreed) {
405 layoutTiles(mCenterX, mCenterY, mScale, mRotation);
406 mIsTextureFreed = false;
407 setScreenNail(mModel == null ? null : mModel.getScreenNail());
412 protected void render(GLCanvas canvas) {
413 mUploadQuota = UPLOAD_LIMIT;
414 mRenderComplete = true;
417 int rotation = mRotation;
419 if (rotation != 0) flags |= GLCanvas.SAVE_FLAG_MATRIX;
424 int centerX = getWidth() / 2, centerY = getHeight() / 2;
425 canvas.translate(centerX, centerY);
426 canvas.rotate(rotation, 0, 0, 1);
427 canvas.translate(-centerX, -centerY);
431 if (level != mLevelCount && !isScreenNailAnimating()) {
432 if (mScreenNail != null) {
433 mScreenNail.noDraw();
436 int size = (TILE_SIZE << level);
437 float length = size * mScale;
440 for (int ty = r.top, i = 0; ty < r.bottom; ty += size, i++) {
441 float y = mOffsetY + i * length;
442 for (int tx = r.left, j = 0; tx < r.right; tx += size, j++) {
443 float x = mOffsetX + j * length;
444 drawTile(canvas, tx, ty, level, x, y, length);
447 } else if (mScreenNail != null) {
448 mScreenNail.draw(canvas, mOffsetX, mOffsetY,
449 Math.round(mImageWidth * mScale),
450 Math.round(mImageHeight * mScale));
451 if (isScreenNailAnimating()) {
456 if (flags != 0) canvas.restore();
459 if (mRenderComplete) {
460 if (!mBackgroundTileUploaded) uploadBackgroundTiles(canvas);
466 private boolean isScreenNailAnimating() {
467 return (mScreenNail instanceof TiledScreenNail)
468 && ((TiledScreenNail) mScreenNail).isAnimating();
471 private void uploadBackgroundTiles(GLCanvas canvas) {
472 mBackgroundTileUploaded = true;
473 int n = mActiveTiles.size();
474 for (int i = 0; i < n; i++) {
475 Tile tile = mActiveTiles.valueAt(i);
476 if (!tile.isContentValid()) queueForDecode(tile);
480 void queueForUpload(Tile tile) {
481 synchronized (this) {
482 mUploadQueue.push(tile);
484 if (mTileUploader.mActive.compareAndSet(false, true)) {
485 getGLRoot().addOnGLIdleListener(mTileUploader);
489 synchronized void queueForDecode(Tile tile) {
490 if (tile.mTileState == STATE_ACTIVATED) {
491 tile.mTileState = STATE_IN_QUEUE;
492 if (mDecodeQueue.push(tile)) notifyAll();
496 boolean decodeTile(Tile tile) {
497 synchronized (this) {
498 if (tile.mTileState != STATE_IN_QUEUE) return false;
499 tile.mTileState = STATE_DECODING;
501 boolean decodeComplete = tile.decode();
502 synchronized (this) {
503 if (tile.mTileState == STATE_RECYCLING) {
504 tile.mTileState = STATE_RECYCLED;
505 if (tile.mDecodedTile != null) {
506 if (sTilePool != null) sTilePool.recycle(tile.mDecodedTile);
507 tile.mDecodedTile = null;
509 mRecycledQueue.push(tile);
512 tile.mTileState = decodeComplete ? STATE_DECODED : STATE_DECODE_FAIL;
513 return decodeComplete;
517 private synchronized Tile obtainTile(int x, int y, int level) {
518 Tile tile = mRecycledQueue.pop();
520 tile.mTileState = STATE_ACTIVATED;
521 tile.update(x, y, level);
524 return new Tile(x, y, level);
527 synchronized void recycleTile(Tile tile) {
528 if (tile.mTileState == STATE_DECODING) {
529 tile.mTileState = STATE_RECYCLING;
532 tile.mTileState = STATE_RECYCLED;
533 if (tile.mDecodedTile != null) {
534 if (sTilePool != null) sTilePool.recycle(tile.mDecodedTile);
535 tile.mDecodedTile = null;
537 mRecycledQueue.push(tile);
540 private void activateTile(int x, int y, int level) {
541 long key = makeTileKey(x, y, level);
542 Tile tile = mActiveTiles.get(key);
544 if (tile.mTileState == STATE_IN_QUEUE) {
545 tile.mTileState = STATE_ACTIVATED;
549 tile = obtainTile(x, y, level);
550 mActiveTiles.put(key, tile);
553 private Tile getTile(int x, int y, int level) {
554 return mActiveTiles.get(makeTileKey(x, y, level));
557 private static long makeTileKey(int x, int y, int level) {
559 result = (result << 16) | y;
560 result = (result << 16) | level;
564 private class TileUploader implements GLRoot.OnGLIdleListener {
565 AtomicBoolean mActive = new AtomicBoolean(false);
568 public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
569 // Skips uploading if there is a pending rendering request.
570 // Returns true to keep uploading in next rendering loop.
571 if (renderRequested) return true;
572 int quota = UPLOAD_LIMIT;
575 synchronized (TileImageView.this) {
576 tile = mUploadQueue.pop();
578 if (tile == null) break;
579 if (!tile.isContentValid()) {
580 boolean hasBeenLoaded = tile.isLoaded();
581 Utils.assertTrue(tile.mTileState == STATE_DECODED);
582 tile.updateContent(canvas);
583 if (!hasBeenLoaded) tile.draw(canvas, 0, 0);
587 if (tile == null) mActive.set(false);
592 // Draw the tile to a square at canvas that locates at (x, y) and
593 // has a side length of length.
594 public void drawTile(GLCanvas canvas,
595 int tx, int ty, int level, float x, float y, float length) {
596 RectF source = mSourceRect;
597 RectF target = mTargetRect;
598 target.set(x, y, x + length, y + length);
599 source.set(0, 0, TILE_SIZE, TILE_SIZE);
601 Tile tile = getTile(tx, ty, level);
603 if (!tile.isContentValid()) {
604 if (tile.mTileState == STATE_DECODED) {
605 if (mUploadQuota > 0) {
607 tile.updateContent(canvas);
609 mRenderComplete = false;
611 } else if (tile.mTileState != STATE_DECODE_FAIL){
612 mRenderComplete = false;
613 queueForDecode(tile);
616 if (drawTile(tile, canvas, source, target)) return;
618 if (mScreenNail != null) {
619 int size = TILE_SIZE << level;
620 float scaleX = (float) mScreenNail.getWidth() / mImageWidth;
621 float scaleY = (float) mScreenNail.getHeight() / mImageHeight;
622 source.set(tx * scaleX, ty * scaleY, (tx + size) * scaleX,
623 (ty + size) * scaleY);
624 mScreenNail.draw(canvas, source, target);
628 static boolean drawTile(
629 Tile tile, GLCanvas canvas, RectF source, RectF target) {
631 if (tile.isContentValid()) {
632 // offset source rectangle for the texture border.
633 source.offset(TILE_BORDER, TILE_BORDER);
634 canvas.drawTexture(tile, source, target);
638 // Parent can be divided to four quads and tile is one of the four.
639 Tile parent = tile.getParentTile();
640 if (parent == null) return false;
641 if (tile.mX == parent.mX) {
645 source.left = (TILE_SIZE + source.left) / 2f;
646 source.right = (TILE_SIZE + source.right) / 2f;
648 if (tile.mY == parent.mY) {
652 source.top = (TILE_SIZE + source.top) / 2f;
653 source.bottom = (TILE_SIZE + source.bottom) / 2f;
659 private class Tile extends UploadedTexture {
662 public int mTileLevel;
664 public Bitmap mDecodedTile;
665 public volatile int mTileState = STATE_ACTIVATED;
667 public Tile(int x, int y, int level) {
674 protected void onFreeBitmap(Bitmap bitmap) {
675 if (sTilePool != null) sTilePool.recycle(bitmap);
679 // Get a tile from the original image. The tile is down-scaled
680 // by (1 << mTilelevel) from a region in the original image.
682 mDecodedTile = DecodeUtils.ensureGLCompatibleBitmap(mModel.getTile(
683 mTileLevel, mX, mY, TILE_SIZE, TILE_BORDER, sTilePool));
684 } catch (Throwable t) {
685 Log.w(TAG, "fail to decode tile", t);
687 return mDecodedTile != null;
691 protected Bitmap onGetBitmap() {
692 Utils.assertTrue(mTileState == STATE_DECODED);
694 // We need to override the width and height, so that we won't
695 // draw beyond the boundaries.
696 int rightEdge = ((mImageWidth - mX) >> mTileLevel) + TILE_BORDER;
697 int bottomEdge = ((mImageHeight - mY) >> mTileLevel) + TILE_BORDER;
698 setSize(Math.min(BITMAP_SIZE, rightEdge), Math.min(BITMAP_SIZE, bottomEdge));
700 Bitmap bitmap = mDecodedTile;
702 mTileState = STATE_ACTIVATED;
706 // We override getTextureWidth() and getTextureHeight() here, so the
707 // texture can be re-used for different tiles regardless of the actual
708 // size of the tile (which may be small because it is a tile at the
711 public int getTextureWidth() {
712 return TILE_SIZE + TILE_BORDER * 2;
716 public int getTextureHeight() {
717 return TILE_SIZE + TILE_BORDER * 2;
720 public void update(int x, int y, int level) {
727 public Tile getParentTile() {
728 if (mTileLevel + 1 == mLevelCount) return null;
729 int size = TILE_SIZE << (mTileLevel + 1);
730 int x = size * (mX / size);
731 int y = size * (mY / size);
732 return getTile(x, y, mTileLevel + 1);
736 public String toString() {
737 return String.format("tile(%s, %s, %s / %s)",
738 mX / TILE_SIZE, mY / TILE_SIZE, mLevel, mLevelCount);
742 private static class TileQueue {
747 if (tile != null) mHead = tile.mNext;
751 public boolean push(Tile tile) {
752 boolean wasEmpty = mHead == null;
758 public void clean() {
763 private class TileDecoder implements ThreadPool.Job<Void> {
765 private CancelListener mNotifier = new CancelListener() {
767 public void onCancel() {
768 synchronized (TileImageView.this) {
769 TileImageView.this.notifyAll();
775 public Void run(JobContext jc) {
776 jc.setMode(ThreadPool.MODE_NONE);
777 jc.setCancelListener(mNotifier);
778 while (!jc.isCancelled()) {
780 synchronized(TileImageView.this) {
781 tile = mDecodeQueue.pop();
782 if (tile == null && !jc.isCancelled()) {
783 Utils.waitWithoutInterrupt(TileImageView.this);
786 if (tile == null) continue;
787 if (decodeTile(tile)) queueForUpload(tile);