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.content.Context;
20 import android.graphics.Bitmap;
21 import android.graphics.Point;
22 import android.graphics.Rect;
23 import android.graphics.RectF;
24 import android.support.v4.util.LongSparseArray;
25 import android.util.DisplayMetrics;
26 import android.util.FloatMath;
27 import android.view.WindowManager;
29 import com.android.gallery3d.app.GalleryContext;
30 import com.android.gallery3d.common.ApiHelper;
31 import com.android.gallery3d.common.Utils;
32 import com.android.gallery3d.data.BitmapPool;
33 import com.android.gallery3d.data.DecodeUtils;
34 import com.android.gallery3d.glrenderer.GLCanvas;
35 import com.android.gallery3d.glrenderer.UploadedTexture;
36 import com.android.gallery3d.util.Future;
37 import com.android.gallery3d.util.ThreadPool;
38 import com.android.gallery3d.util.ThreadPool.CancelListener;
39 import com.android.gallery3d.util.ThreadPool.JobContext;
41 import java.util.concurrent.atomic.AtomicBoolean;
43 public class TileImageView extends GLView {
44 public static final int SIZE_UNKNOWN = -1;
46 @SuppressWarnings("unused")
47 private static final String TAG = "TileImageView";
48 private static final int UPLOAD_LIMIT = 1;
50 // TILE_SIZE must be 2^N
51 private static int sTileSize;
53 private static BitmapPool sTilePool;
56 * This is the tile state in the CPU side.
58 * ACTIVATED (initial state)
59 * --> IN_QUEUE - by queueForDecode()
60 * --> RECYCLED - by recycleTile()
61 * IN_QUEUE --> DECODING - by decodeTile()
62 * --> RECYCLED - by recycleTile)
63 * DECODING --> RECYCLING - by recycleTile()
64 * --> DECODED - by decodeTile()
65 * --> DECODE_FAIL - by decodeTile()
66 * RECYCLING --> RECYCLED - by decodeTile()
67 * DECODED --> ACTIVATED - (after the decoded bitmap is uploaded)
68 * DECODED --> RECYCLED - by recycleTile()
69 * DECODE_FAIL -> RECYCLED - by recycleTile()
70 * RECYCLED --> ACTIVATED - by obtainTile()
72 private static final int STATE_ACTIVATED = 0x01;
73 private static final int STATE_IN_QUEUE = 0x02;
74 private static final int STATE_DECODING = 0x04;
75 private static final int STATE_DECODED = 0x08;
76 private static final int STATE_DECODE_FAIL = 0x10;
77 private static final int STATE_RECYCLING = 0x20;
78 private static final int STATE_RECYCLED = 0x40;
80 private TileSource mModel;
81 private ScreenNail mScreenNail;
82 protected int mLevelCount; // cache the value of mScaledBitmaps.length
84 // The mLevel variable indicates which level of bitmap we should use.
85 // Level 0 means the original full-sized bitmap, and a larger value means
86 // a smaller scaled bitmap (The width and height of each scaled bitmap is
87 // half size of the previous one). If the value is in [0, mLevelCount), we
88 // use the bitmap in mScaledBitmaps[mLevel] for display, otherwise the value
89 // is mLevelCount, and that means we use mScreenNail for display.
90 private int mLevel = 0;
92 // The offsets of the (left, top) of the upper-left tile to the (left, top)
97 private int mUploadQuota;
98 private boolean mRenderComplete;
100 private final RectF mSourceRect = new RectF();
101 private final RectF mTargetRect = new RectF();
103 private final LongSparseArray<Tile> mActiveTiles = new LongSparseArray<Tile>();
105 // The following three queue is guarded by TileImageView.this
106 private final TileQueue mRecycledQueue = new TileQueue();
107 private final TileQueue mUploadQueue = new TileQueue();
108 private final TileQueue mDecodeQueue = new TileQueue();
110 // The width and height of the full-sized bitmap
111 protected int mImageWidth = SIZE_UNKNOWN;
112 protected int mImageHeight = SIZE_UNKNOWN;
114 protected int mCenterX;
115 protected int mCenterY;
116 protected float mScale;
117 protected int mRotation;
119 // Temp variables to avoid memory allocation
120 private final Rect mTileRange = new Rect();
121 private final Rect mActiveRange[] = {new Rect(), new Rect()};
123 private final TileUploader mTileUploader = new TileUploader();
124 private boolean mIsTextureFreed;
125 private Future<Void> mTileDecoder;
126 private final ThreadPool mThreadPool;
127 private boolean mBackgroundTileUploaded;
129 public static interface TileSource {
130 public int getLevelCount();
131 public ScreenNail getScreenNail();
132 public int getImageWidth();
133 public int getImageHeight();
135 // The tile returned by this method can be specified this way: Assuming
136 // the image size is (width, height), first take the intersection of (0,
137 // 0) - (width, height) and (x, y) - (x + tileSize, y + tileSize). 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,
150 public static boolean isHighResolution(Context context) {
151 DisplayMetrics metrics = new DisplayMetrics();
152 WindowManager wm = (WindowManager)
153 context.getSystemService(Context.WINDOW_SERVICE);
154 wm.getDefaultDisplay().getMetrics(metrics);
155 return metrics.heightPixels > 2048 || metrics.widthPixels > 2048;
158 public TileImageView(GalleryContext context) {
159 mThreadPool = context.getThreadPool();
160 mTileDecoder = mThreadPool.submit(new TileDecoder());
161 if (sTileSize == 0) {
162 if (isHighResolution(context.getAndroidContext())) {
168 ApiHelper.HAS_REUSING_BITMAP_IN_BITMAP_REGION_DECODER
169 ? new BitmapPool(sTileSize, sTileSize, 128)
174 public void setModel(TileSource model) {
176 if (model != null) notifyModelInvalidated();
179 public void setScreenNail(ScreenNail s) {
183 public void notifyModelInvalidated() {
185 if (mModel == null) {
191 setScreenNail(mModel.getScreenNail());
192 mImageWidth = mModel.getImageWidth();
193 mImageHeight = mModel.getImageHeight();
194 mLevelCount = mModel.getLevelCount();
196 layoutTiles(mCenterX, mCenterY, mScale, mRotation);
201 protected void onLayout(
202 boolean changeSize, int left, int top, int right, int bottom) {
203 super.onLayout(changeSize, left, top, right, bottom);
204 if (changeSize) layoutTiles(mCenterX, mCenterY, mScale, mRotation);
207 // Prepare the tiles we want to use for display.
209 // 1. Decide the tile level we want to use for display.
210 // 2. Decide the tile levels we want to keep as texture (in addition to
211 // the one we use for display).
212 // 3. Recycle unused tiles.
213 // 4. Activate the tiles we want.
214 private void layoutTiles(int centerX, int centerY, float scale, int rotation) {
215 // The width and height of this view.
216 int width = getWidth();
217 int height = getHeight();
219 // The tile levels we want to keep as texture is in the range
220 // [fromLevel, endLevel).
224 // We want to use a texture larger than or equal to the display size.
225 mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount);
227 // We want to keep one more tile level as texture in addition to what
228 // we use for display. So it can be faster when the scale moves to the
229 // next level. We choose a level closer to the current scale.
230 if (mLevel != mLevelCount) {
231 Rect range = mTileRange;
232 getRange(range, centerX, centerY, mLevel, scale, rotation);
233 mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale);
234 mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale);
235 fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel;
237 // Activate the tiles of the smallest two levels.
238 fromLevel = mLevel - 2;
239 mOffsetX = Math.round(width / 2f - centerX * scale);
240 mOffsetY = Math.round(height / 2f - centerY * scale);
243 fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2));
244 endLevel = Math.min(fromLevel + 2, mLevelCount);
246 Rect range[] = mActiveRange;
247 for (int i = fromLevel; i < endLevel; ++i) {
248 getRange(range[i - fromLevel], centerX, centerY, i, rotation);
251 // If rotation is transient, don't update the tile.
252 if (rotation % 90 != 0) return;
254 synchronized (this) {
255 mDecodeQueue.clean();
256 mUploadQueue.clean();
257 mBackgroundTileUploaded = false;
259 // Recycle unused tiles: if the level of the active tile is outside the
260 // range [fromLevel, endLevel) or not in the visible range.
261 int n = mActiveTiles.size();
262 for (int i = 0; i < n; i++) {
263 Tile tile = mActiveTiles.valueAt(i);
264 int level = tile.mTileLevel;
265 if (level < fromLevel || level >= endLevel
266 || !range[level - fromLevel].contains(tile.mX, tile.mY)) {
267 mActiveTiles.removeAt(i);
275 for (int i = fromLevel; i < endLevel; ++i) {
276 int size = sTileSize << i;
277 Rect r = range[i - fromLevel];
278 for (int y = r.top, bottom = r.bottom; y < bottom; y += size) {
279 for (int x = r.left, right = r.right; x < right; x += size) {
280 activateTile(x, y, i);
287 protected synchronized void invalidateTiles() {
288 mDecodeQueue.clean();
289 mUploadQueue.clean();
291 // TODO disable decoder
292 int n = mActiveTiles.size();
293 for (int i = 0; i < n; i++) {
294 Tile tile = mActiveTiles.valueAt(i);
297 mActiveTiles.clear();
300 private void getRange(Rect out, int cX, int cY, int level, int rotation) {
301 getRange(out, cX, cY, level, 1f / (1 << (level + 1)), rotation);
304 // If the bitmap is scaled by the given factor "scale", return the
305 // rectangle containing visible range. The left-top coordinate returned is
306 // aligned to the tile boundary.
308 // (cX, cY) is the point on the original bitmap which will be put in the
309 // center of the ImageViewer.
310 private void getRange(Rect out,
311 int cX, int cY, int level, float scale, int rotation) {
313 double radians = Math.toRadians(-rotation);
314 double w = getWidth();
315 double h = getHeight();
317 double cos = Math.cos(radians);
318 double sin = Math.sin(radians);
319 int width = (int) Math.ceil(Math.max(
320 Math.abs(cos * w - sin * h), Math.abs(cos * w + sin * h)));
321 int height = (int) Math.ceil(Math.max(
322 Math.abs(sin * w + cos * h), Math.abs(sin * w - cos * h)));
324 int left = (int) FloatMath.floor(cX - width / (2f * scale));
325 int top = (int) FloatMath.floor(cY - height / (2f * scale));
326 int right = (int) FloatMath.ceil(left + width / scale);
327 int bottom = (int) FloatMath.ceil(top + height / scale);
329 // align the rectangle to tile boundary
330 int size = sTileSize << level;
331 left = Math.max(0, size * (left / size));
332 top = Math.max(0, size * (top / size));
333 right = Math.min(mImageWidth, right);
334 bottom = Math.min(mImageHeight, bottom);
336 out.set(left, top, right, bottom);
339 // Calculate where the center of the image is, in the view coordinates.
340 public void getImageCenter(Point center) {
341 // The width and height of this view.
342 int viewW = getWidth();
343 int viewH = getHeight();
345 // The distance between the center of the view to the center of the
346 // bitmap, in bitmap units. (mCenterX and mCenterY are the bitmap
347 // coordinates correspond to the center of view)
349 if (mRotation % 180 == 0) {
350 distW = mImageWidth / 2 - mCenterX;
351 distH = mImageHeight / 2 - mCenterY;
353 distW = mImageHeight / 2 - mCenterY;
354 distH = mImageWidth / 2 - mCenterX;
357 // Convert to view coordinates. mScale translates from bitmap units to
359 center.x = Math.round(viewW / 2f + distW * mScale);
360 center.y = Math.round(viewH / 2f + distH * mScale);
363 public boolean setPosition(int centerX, int centerY, float scale, int rotation) {
364 if (mCenterX == centerX && mCenterY == centerY
365 && mScale == scale && mRotation == rotation) return false;
369 mRotation = rotation;
370 layoutTiles(centerX, centerY, scale, rotation);
375 public void freeTextures() {
376 mIsTextureFreed = true;
378 if (mTileDecoder != null) {
379 mTileDecoder.cancel();
384 int n = mActiveTiles.size();
385 for (int i = 0; i < n; i++) {
386 Tile texture = mActiveTiles.valueAt(i);
389 mActiveTiles.clear();
390 mTileRange.set(0, 0, 0, 0);
392 synchronized (this) {
393 mUploadQueue.clean();
394 mDecodeQueue.clean();
395 Tile tile = mRecycledQueue.pop();
396 while (tile != null) {
398 tile = mRecycledQueue.pop();
402 if (sTilePool != null) sTilePool.clear();
405 public void prepareTextures() {
406 if (mTileDecoder == null) {
407 mTileDecoder = mThreadPool.submit(new TileDecoder());
409 if (mIsTextureFreed) {
410 layoutTiles(mCenterX, mCenterY, mScale, mRotation);
411 mIsTextureFreed = false;
412 setScreenNail(mModel == null ? null : mModel.getScreenNail());
417 protected void render(GLCanvas canvas) {
418 mUploadQuota = UPLOAD_LIMIT;
419 mRenderComplete = true;
422 int rotation = mRotation;
424 if (rotation != 0) flags |= GLCanvas.SAVE_FLAG_MATRIX;
429 int centerX = getWidth() / 2, centerY = getHeight() / 2;
430 canvas.translate(centerX, centerY);
431 canvas.rotate(rotation, 0, 0, 1);
432 canvas.translate(-centerX, -centerY);
436 if (level != mLevelCount && !isScreenNailAnimating()) {
437 if (mScreenNail != null) {
438 mScreenNail.noDraw();
441 int size = (sTileSize << level);
442 float length = size * mScale;
445 for (int ty = r.top, i = 0; ty < r.bottom; ty += size, i++) {
446 float y = mOffsetY + i * length;
447 for (int tx = r.left, j = 0; tx < r.right; tx += size, j++) {
448 float x = mOffsetX + j * length;
449 drawTile(canvas, tx, ty, level, x, y, length);
452 } else if (mScreenNail != null) {
453 mScreenNail.draw(canvas, mOffsetX, mOffsetY,
454 Math.round(mImageWidth * mScale),
455 Math.round(mImageHeight * mScale));
456 if (isScreenNailAnimating()) {
461 if (flags != 0) canvas.restore();
464 if (mRenderComplete) {
465 if (!mBackgroundTileUploaded) uploadBackgroundTiles(canvas);
471 private boolean isScreenNailAnimating() {
472 return (mScreenNail instanceof TiledScreenNail)
473 && ((TiledScreenNail) mScreenNail).isAnimating();
476 private void uploadBackgroundTiles(GLCanvas canvas) {
477 mBackgroundTileUploaded = true;
478 int n = mActiveTiles.size();
479 for (int i = 0; i < n; i++) {
480 Tile tile = mActiveTiles.valueAt(i);
481 if (!tile.isContentValid()) queueForDecode(tile);
485 void queueForUpload(Tile tile) {
486 synchronized (this) {
487 mUploadQueue.push(tile);
489 if (mTileUploader.mActive.compareAndSet(false, true)) {
490 getGLRoot().addOnGLIdleListener(mTileUploader);
494 synchronized void queueForDecode(Tile tile) {
495 if (tile.mTileState == STATE_ACTIVATED) {
496 tile.mTileState = STATE_IN_QUEUE;
497 if (mDecodeQueue.push(tile)) notifyAll();
501 boolean decodeTile(Tile tile) {
502 synchronized (this) {
503 if (tile.mTileState != STATE_IN_QUEUE) return false;
504 tile.mTileState = STATE_DECODING;
506 boolean decodeComplete = tile.decode();
507 synchronized (this) {
508 if (tile.mTileState == STATE_RECYCLING) {
509 tile.mTileState = STATE_RECYCLED;
510 if (tile.mDecodedTile != null) {
511 if (sTilePool != null) sTilePool.recycle(tile.mDecodedTile);
512 tile.mDecodedTile = null;
514 mRecycledQueue.push(tile);
517 tile.mTileState = decodeComplete ? STATE_DECODED : STATE_DECODE_FAIL;
518 return decodeComplete;
522 private synchronized Tile obtainTile(int x, int y, int level) {
523 Tile tile = mRecycledQueue.pop();
525 tile.mTileState = STATE_ACTIVATED;
526 tile.update(x, y, level);
529 return new Tile(x, y, level);
532 synchronized void recycleTile(Tile tile) {
533 if (tile.mTileState == STATE_DECODING) {
534 tile.mTileState = STATE_RECYCLING;
537 tile.mTileState = STATE_RECYCLED;
538 if (tile.mDecodedTile != null) {
539 if (sTilePool != null) sTilePool.recycle(tile.mDecodedTile);
540 tile.mDecodedTile = null;
542 mRecycledQueue.push(tile);
545 private void activateTile(int x, int y, int level) {
546 long key = makeTileKey(x, y, level);
547 Tile tile = mActiveTiles.get(key);
549 if (tile.mTileState == STATE_IN_QUEUE) {
550 tile.mTileState = STATE_ACTIVATED;
554 tile = obtainTile(x, y, level);
555 mActiveTiles.put(key, tile);
558 private Tile getTile(int x, int y, int level) {
559 return mActiveTiles.get(makeTileKey(x, y, level));
562 private static long makeTileKey(int x, int y, int level) {
564 result = (result << 16) | y;
565 result = (result << 16) | level;
569 private class TileUploader implements GLRoot.OnGLIdleListener {
570 AtomicBoolean mActive = new AtomicBoolean(false);
573 public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
574 // Skips uploading if there is a pending rendering request.
575 // Returns true to keep uploading in next rendering loop.
576 if (renderRequested) return true;
577 int quota = UPLOAD_LIMIT;
580 synchronized (TileImageView.this) {
581 tile = mUploadQueue.pop();
583 if (tile == null) break;
584 if (!tile.isContentValid()) {
585 boolean hasBeenLoaded = tile.isLoaded();
586 Utils.assertTrue(tile.mTileState == STATE_DECODED);
587 tile.updateContent(canvas);
588 if (!hasBeenLoaded) tile.draw(canvas, 0, 0);
592 if (tile == null) mActive.set(false);
597 // Draw the tile to a square at canvas that locates at (x, y) and
598 // has a side length of length.
599 public void drawTile(GLCanvas canvas,
600 int tx, int ty, int level, float x, float y, float length) {
601 RectF source = mSourceRect;
602 RectF target = mTargetRect;
603 target.set(x, y, x + length, y + length);
604 source.set(0, 0, sTileSize, sTileSize);
606 Tile tile = getTile(tx, ty, level);
608 if (!tile.isContentValid()) {
609 if (tile.mTileState == STATE_DECODED) {
610 if (mUploadQuota > 0) {
612 tile.updateContent(canvas);
614 mRenderComplete = false;
616 } else if (tile.mTileState != STATE_DECODE_FAIL){
617 mRenderComplete = false;
618 queueForDecode(tile);
621 if (drawTile(tile, canvas, source, target)) return;
623 if (mScreenNail != null) {
624 int size = sTileSize << level;
625 float scaleX = (float) mScreenNail.getWidth() / mImageWidth;
626 float scaleY = (float) mScreenNail.getHeight() / mImageHeight;
627 source.set(tx * scaleX, ty * scaleY, (tx + size) * scaleX,
628 (ty + size) * scaleY);
629 mScreenNail.draw(canvas, source, target);
633 static boolean drawTile(
634 Tile tile, GLCanvas canvas, RectF source, RectF target) {
636 if (tile.isContentValid()) {
637 canvas.drawTexture(tile, source, target);
641 // Parent can be divided to four quads and tile is one of the four.
642 Tile parent = tile.getParentTile();
643 if (parent == null) return false;
644 if (tile.mX == parent.mX) {
648 source.left = (sTileSize + source.left) / 2f;
649 source.right = (sTileSize + source.right) / 2f;
651 if (tile.mY == parent.mY) {
655 source.top = (sTileSize + source.top) / 2f;
656 source.bottom = (sTileSize + source.bottom) / 2f;
662 private class Tile extends UploadedTexture {
665 public int mTileLevel;
667 public Bitmap mDecodedTile;
668 public volatile int mTileState = STATE_ACTIVATED;
670 public Tile(int x, int y, int level) {
677 protected void onFreeBitmap(Bitmap bitmap) {
678 if (sTilePool != null) sTilePool.recycle(bitmap);
682 // Get a tile from the original image. The tile is down-scaled
683 // by (1 << mTilelevel) from a region in the original image.
685 mDecodedTile = DecodeUtils.ensureGLCompatibleBitmap(mModel.getTile(
686 mTileLevel, mX, mY, sTileSize, sTilePool));
687 } catch (Throwable t) {
688 Log.w(TAG, "fail to decode tile", t);
690 return mDecodedTile != null;
694 protected Bitmap onGetBitmap() {
695 Utils.assertTrue(mTileState == STATE_DECODED);
697 // We need to override the width and height, so that we won't
698 // draw beyond the boundaries.
699 int rightEdge = ((mImageWidth - mX) >> mTileLevel);
700 int bottomEdge = ((mImageHeight - mY) >> mTileLevel);
701 setSize(Math.min(sTileSize, rightEdge), Math.min(sTileSize, bottomEdge));
703 Bitmap bitmap = mDecodedTile;
705 mTileState = STATE_ACTIVATED;
709 // We override getTextureWidth() and getTextureHeight() here, so the
710 // texture can be re-used for different tiles regardless of the actual
711 // size of the tile (which may be small because it is a tile at the
714 public int getTextureWidth() {
719 public int getTextureHeight() {
723 public void update(int x, int y, int level) {
730 public Tile getParentTile() {
731 if (mTileLevel + 1 == mLevelCount) return null;
732 int size = sTileSize << (mTileLevel + 1);
733 int x = size * (mX / size);
734 int y = size * (mY / size);
735 return getTile(x, y, mTileLevel + 1);
739 public String toString() {
740 return String.format("tile(%s, %s, %s / %s)",
741 mX / sTileSize, mY / sTileSize, mLevel, mLevelCount);
745 private static class TileQueue {
750 if (tile != null) mHead = tile.mNext;
754 public boolean push(Tile tile) {
755 boolean wasEmpty = mHead == null;
761 public void clean() {
766 private class TileDecoder implements ThreadPool.Job<Void> {
768 private CancelListener mNotifier = new CancelListener() {
770 public void onCancel() {
771 synchronized (TileImageView.this) {
772 TileImageView.this.notifyAll();
778 public Void run(JobContext jc) {
779 jc.setMode(ThreadPool.MODE_NONE);
780 jc.setCancelListener(mNotifier);
781 while (!jc.isCancelled()) {
783 synchronized(TileImageView.this) {
784 tile = mDecodeQueue.pop();
785 if (tile == null && !jc.isCancelled()) {
786 Utils.waitWithoutInterrupt(TileImageView.this);
789 if (tile == null) continue;
790 if (decodeTile(tile)) queueForUpload(tile);