OSDN Git Service

Merge "GL packaging refactor" into gb-ub-photos-bryce
[android-x86/packages-apps-Gallery2.git] / src / com / android / gallery3d / ui / TileImageView.java
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.android.gallery3d.ui;
18
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;
24
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;
38
39 import java.util.concurrent.atomic.AtomicBoolean;
40
41 public class TileImageView extends GLView {
42     public static final int SIZE_UNKNOWN = -1;
43
44     @SuppressWarnings("unused")
45     private static final String TAG = "TileImageView";
46
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;
53
54     private static BitmapPool sTilePool;
55
56     /*
57      *  This is the tile state in the CPU side.
58      *  Life of a Tile:
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()
72      */
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;
80
81     private Model mModel;
82     private ScreenNail mScreenNail;
83     protected int mLevelCount;  // cache the value of mScaledBitmaps.length
84
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;
92
93     // The offsets of the (left, top) of the upper-left tile to the (left, top)
94     // of the view.
95     private int mOffsetX;
96     private int mOffsetY;
97
98     private int mUploadQuota;
99     private boolean mRenderComplete;
100
101     private final RectF mSourceRect = new RectF();
102     private final RectF mTargetRect = new RectF();
103
104     private final LongSparseArray<Tile> mActiveTiles = new LongSparseArray<Tile>();
105
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();
110
111     // The width and height of the full-sized bitmap
112     protected int mImageWidth = SIZE_UNKNOWN;
113     protected int mImageHeight = SIZE_UNKNOWN;
114
115     protected int mCenterX;
116     protected int mCenterY;
117     protected float mScale;
118     protected int mRotation;
119
120     // Temp variables to avoid memory allocation
121     private final Rect mTileRange = new Rect();
122     private final Rect mActiveRange[] = {new Rect(), new Rect()};
123
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;
129
130     public static interface Model {
131         public int getLevelCount();
132         public ScreenNail getScreenNail();
133         public int getImageWidth();
134         public int getImageHeight();
135
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.
142         //
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.
146         //
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);
150     }
151
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())) {
157                 TILE_SIZE = 510 ;
158             } else {
159                 TILE_SIZE = 254;
160             }
161             BITMAP_SIZE = TILE_SIZE + TILE_BORDER * 2;
162             sTilePool =
163                     ApiHelper.HAS_REUSING_BITMAP_IN_BITMAP_REGION_DECODER
164                     ? new BitmapPool(BITMAP_SIZE, BITMAP_SIZE, 128)
165                     : null;
166         }
167     }
168
169     public void setModel(Model model) {
170         mModel = model;
171         if (model != null) notifyModelInvalidated();
172     }
173
174     public void setScreenNail(ScreenNail s) {
175         mScreenNail = s;
176     }
177
178     public void notifyModelInvalidated() {
179         invalidateTiles();
180         if (mModel == null) {
181             mScreenNail = null;
182             mImageWidth = 0;
183             mImageHeight = 0;
184             mLevelCount = 0;
185         } else {
186             setScreenNail(mModel.getScreenNail());
187             mImageWidth = mModel.getImageWidth();
188             mImageHeight = mModel.getImageHeight();
189             mLevelCount = mModel.getLevelCount();
190         }
191         layoutTiles(mCenterX, mCenterY, mScale, mRotation);
192         invalidate();
193     }
194
195     @Override
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);
200     }
201
202     // Prepare the tiles we want to use for display.
203     //
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();
213
214         // The tile levels we want to keep as texture is in the range
215         // [fromLevel, endLevel).
216         int fromLevel;
217         int endLevel;
218
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);
221
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;
231         } else {
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);
236         }
237
238         fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2));
239         endLevel = Math.min(fromLevel + 2, mLevelCount);
240
241         Rect range[] = mActiveRange;
242         for (int i = fromLevel; i < endLevel; ++i) {
243             getRange(range[i - fromLevel], centerX, centerY, i, rotation);
244         }
245
246         // If rotation is transient, don't update the tile.
247         if (rotation % 90 != 0) return;
248
249         synchronized (this) {
250             mDecodeQueue.clean();
251             mUploadQueue.clean();
252             mBackgroundTileUploaded = false;
253
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);
263                     i--;
264                     n--;
265                     recycleTile(tile);
266                 }
267             }
268         }
269
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);
276                 }
277             }
278         }
279         invalidate();
280     }
281
282     protected synchronized void invalidateTiles() {
283         mDecodeQueue.clean();
284         mUploadQueue.clean();
285
286         // TODO disable decoder
287         int n = mActiveTiles.size();
288         for (int i = 0; i < n; i++) {
289             Tile tile = mActiveTiles.valueAt(i);
290             recycleTile(tile);
291         }
292         mActiveTiles.clear();
293     }
294
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);
297     }
298
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.
302     //
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) {
307
308         double radians = Math.toRadians(-rotation);
309         double w = getWidth();
310         double h = getHeight();
311
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)));
318
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);
323
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);
330
331         out.set(left, top, right, bottom);
332     }
333
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();
339
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)
343         int distW, distH;
344         if (mRotation % 180 == 0) {
345             distW = mImageWidth / 2 - mCenterX;
346             distH = mImageHeight / 2 - mCenterY;
347         } else {
348             distW = mImageHeight / 2 - mCenterY;
349             distH = mImageWidth / 2 - mCenterX;
350         }
351
352         // Convert to view coordinates. mScale translates from bitmap units to
353         // view units.
354         center.x = Math.round(viewW / 2f + distW * mScale);
355         center.y = Math.round(viewH / 2f + distH * mScale);
356     }
357
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;
361         mCenterX = centerX;
362         mCenterY = centerY;
363         mScale = scale;
364         mRotation = rotation;
365         layoutTiles(centerX, centerY, scale, rotation);
366         invalidate();
367         return true;
368     }
369
370     public void freeTextures() {
371         mIsTextureFreed = true;
372
373         if (mTileDecoder != null) {
374             mTileDecoder.cancel();
375             mTileDecoder.get();
376             mTileDecoder = null;
377         }
378
379         int n = mActiveTiles.size();
380         for (int i = 0; i < n; i++) {
381             Tile texture = mActiveTiles.valueAt(i);
382             texture.recycle();
383         }
384         mActiveTiles.clear();
385         mTileRange.set(0, 0, 0, 0);
386
387         synchronized (this) {
388             mUploadQueue.clean();
389             mDecodeQueue.clean();
390             Tile tile = mRecycledQueue.pop();
391             while (tile != null) {
392                 tile.recycle();
393                 tile = mRecycledQueue.pop();
394             }
395         }
396         setScreenNail(null);
397         if (sTilePool != null) sTilePool.clear();
398     }
399
400     public void prepareTextures() {
401         if (mTileDecoder == null) {
402             mTileDecoder = mThreadPool.submit(new TileDecoder());
403         }
404         if (mIsTextureFreed) {
405             layoutTiles(mCenterX, mCenterY, mScale, mRotation);
406             mIsTextureFreed = false;
407             setScreenNail(mModel == null ? null : mModel.getScreenNail());
408         }
409     }
410
411     @Override
412     protected void render(GLCanvas canvas) {
413         mUploadQuota = UPLOAD_LIMIT;
414         mRenderComplete = true;
415
416         int level = mLevel;
417         int rotation = mRotation;
418         int flags = 0;
419         if (rotation != 0) flags |= GLCanvas.SAVE_FLAG_MATRIX;
420
421         if (flags != 0) {
422             canvas.save(flags);
423             if (rotation != 0) {
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);
428             }
429         }
430         try {
431             if (level != mLevelCount && !isScreenNailAnimating()) {
432                 if (mScreenNail != null) {
433                     mScreenNail.noDraw();
434                 }
435
436                 int size = (TILE_SIZE << level);
437                 float length = size * mScale;
438                 Rect r = mTileRange;
439
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);
445                     }
446                 }
447             } else if (mScreenNail != null) {
448                 mScreenNail.draw(canvas, mOffsetX, mOffsetY,
449                         Math.round(mImageWidth * mScale),
450                         Math.round(mImageHeight * mScale));
451                 if (isScreenNailAnimating()) {
452                     invalidate();
453                 }
454             }
455         } finally {
456             if (flags != 0) canvas.restore();
457         }
458
459         if (mRenderComplete) {
460             if (!mBackgroundTileUploaded) uploadBackgroundTiles(canvas);
461         } else {
462             invalidate();
463         }
464     }
465
466     private boolean isScreenNailAnimating() {
467         return (mScreenNail instanceof TiledScreenNail)
468                 && ((TiledScreenNail) mScreenNail).isAnimating();
469     }
470
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);
477         }
478     }
479
480     void queueForUpload(Tile tile) {
481         synchronized (this) {
482             mUploadQueue.push(tile);
483         }
484         if (mTileUploader.mActive.compareAndSet(false, true)) {
485             getGLRoot().addOnGLIdleListener(mTileUploader);
486         }
487     }
488
489     synchronized void queueForDecode(Tile tile) {
490         if (tile.mTileState == STATE_ACTIVATED) {
491             tile.mTileState = STATE_IN_QUEUE;
492             if (mDecodeQueue.push(tile)) notifyAll();
493         }
494     }
495
496     boolean decodeTile(Tile tile) {
497         synchronized (this) {
498             if (tile.mTileState != STATE_IN_QUEUE) return false;
499             tile.mTileState = STATE_DECODING;
500         }
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;
508                 }
509                 mRecycledQueue.push(tile);
510                 return false;
511             }
512             tile.mTileState = decodeComplete ? STATE_DECODED : STATE_DECODE_FAIL;
513             return decodeComplete;
514         }
515     }
516
517     private synchronized Tile obtainTile(int x, int y, int level) {
518         Tile tile = mRecycledQueue.pop();
519         if (tile != null) {
520             tile.mTileState = STATE_ACTIVATED;
521             tile.update(x, y, level);
522             return tile;
523         }
524         return new Tile(x, y, level);
525     }
526
527     synchronized void recycleTile(Tile tile) {
528         if (tile.mTileState == STATE_DECODING) {
529             tile.mTileState = STATE_RECYCLING;
530             return;
531         }
532         tile.mTileState = STATE_RECYCLED;
533         if (tile.mDecodedTile != null) {
534             if (sTilePool != null) sTilePool.recycle(tile.mDecodedTile);
535             tile.mDecodedTile = null;
536         }
537         mRecycledQueue.push(tile);
538     }
539
540     private void activateTile(int x, int y, int level) {
541         long key = makeTileKey(x, y, level);
542         Tile tile = mActiveTiles.get(key);
543         if (tile != null) {
544             if (tile.mTileState == STATE_IN_QUEUE) {
545                 tile.mTileState = STATE_ACTIVATED;
546             }
547             return;
548         }
549         tile = obtainTile(x, y, level);
550         mActiveTiles.put(key, tile);
551     }
552
553     private Tile getTile(int x, int y, int level) {
554         return mActiveTiles.get(makeTileKey(x, y, level));
555     }
556
557     private static long makeTileKey(int x, int y, int level) {
558         long result = x;
559         result = (result << 16) | y;
560         result = (result << 16) | level;
561         return result;
562     }
563
564     private class TileUploader implements GLRoot.OnGLIdleListener {
565         AtomicBoolean mActive = new AtomicBoolean(false);
566
567         @Override
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;
573             Tile tile = null;
574             while (quota > 0) {
575                 synchronized (TileImageView.this) {
576                     tile = mUploadQueue.pop();
577                 }
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);
584                     --quota;
585                 }
586             }
587             if (tile == null) mActive.set(false);
588             return tile != null;
589         }
590     }
591
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);
600
601         Tile tile = getTile(tx, ty, level);
602         if (tile != null) {
603             if (!tile.isContentValid()) {
604                 if (tile.mTileState == STATE_DECODED) {
605                     if (mUploadQuota > 0) {
606                         --mUploadQuota;
607                         tile.updateContent(canvas);
608                     } else {
609                         mRenderComplete = false;
610                     }
611                 } else if (tile.mTileState != STATE_DECODE_FAIL){
612                     mRenderComplete = false;
613                     queueForDecode(tile);
614                 }
615             }
616             if (drawTile(tile, canvas, source, target)) return;
617         }
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);
625         }
626     }
627
628     static boolean drawTile(
629             Tile tile, GLCanvas canvas, RectF source, RectF target) {
630         while (true) {
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);
635                 return true;
636             }
637
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) {
642                 source.left /= 2f;
643                 source.right /= 2f;
644             } else {
645                 source.left = (TILE_SIZE + source.left) / 2f;
646                 source.right = (TILE_SIZE + source.right) / 2f;
647             }
648             if (tile.mY == parent.mY) {
649                 source.top /= 2f;
650                 source.bottom /= 2f;
651             } else {
652                 source.top = (TILE_SIZE + source.top) / 2f;
653                 source.bottom = (TILE_SIZE + source.bottom) / 2f;
654             }
655             tile = parent;
656         }
657     }
658
659     private class Tile extends UploadedTexture {
660         public int mX;
661         public int mY;
662         public int mTileLevel;
663         public Tile mNext;
664         public Bitmap mDecodedTile;
665         public volatile int mTileState = STATE_ACTIVATED;
666
667         public Tile(int x, int y, int level) {
668             mX = x;
669             mY = y;
670             mTileLevel = level;
671         }
672
673         @Override
674         protected void onFreeBitmap(Bitmap bitmap) {
675             if (sTilePool != null) sTilePool.recycle(bitmap);
676         }
677
678         boolean decode() {
679             // Get a tile from the original image. The tile is down-scaled
680             // by (1 << mTilelevel) from a region in the original image.
681             try {
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);
686             }
687             return mDecodedTile != null;
688         }
689
690         @Override
691         protected Bitmap onGetBitmap() {
692             Utils.assertTrue(mTileState == STATE_DECODED);
693
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));
699
700             Bitmap bitmap = mDecodedTile;
701             mDecodedTile = null;
702             mTileState = STATE_ACTIVATED;
703             return bitmap;
704         }
705
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
709         // boundary).
710         @Override
711         public int getTextureWidth() {
712             return TILE_SIZE + TILE_BORDER * 2;
713         }
714
715         @Override
716         public int getTextureHeight() {
717             return TILE_SIZE + TILE_BORDER * 2;
718         }
719
720         public void update(int x, int y, int level) {
721             mX = x;
722             mY = y;
723             mTileLevel = level;
724             invalidateContent();
725         }
726
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);
733         }
734
735         @Override
736         public String toString() {
737             return String.format("tile(%s, %s, %s / %s)",
738                     mX / TILE_SIZE, mY / TILE_SIZE, mLevel, mLevelCount);
739         }
740     }
741
742     private static class TileQueue {
743         private Tile mHead;
744
745         public Tile pop() {
746             Tile tile = mHead;
747             if (tile != null) mHead = tile.mNext;
748             return tile;
749         }
750
751         public boolean push(Tile tile) {
752             boolean wasEmpty = mHead == null;
753             tile.mNext = mHead;
754             mHead = tile;
755             return wasEmpty;
756         }
757
758         public void clean() {
759             mHead = null;
760         }
761     }
762
763     private class TileDecoder implements ThreadPool.Job<Void> {
764
765         private CancelListener mNotifier = new CancelListener() {
766             @Override
767             public void onCancel() {
768                 synchronized (TileImageView.this) {
769                     TileImageView.this.notifyAll();
770                 }
771             }
772         };
773
774         @Override
775         public Void run(JobContext jc) {
776             jc.setMode(ThreadPool.MODE_NONE);
777             jc.setCancelListener(mNotifier);
778             while (!jc.isCancelled()) {
779                 Tile tile = null;
780                 synchronized(TileImageView.this) {
781                     tile = mDecodeQueue.pop();
782                     if (tile == null && !jc.isCancelled()) {
783                         Utils.waitWithoutInterrupt(TileImageView.this);
784                     }
785                 }
786                 if (tile == null) continue;
787                 if (decodeTile(tile)) queueForUpload(tile);
788             }
789             return null;
790         }
791     }
792 }