OSDN Git Service

am 030f8dad: Fixes bugs in TiledTexture.
[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.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;
36
37 import java.util.concurrent.atomic.AtomicBoolean;
38
39 public class TileImageView extends GLView {
40     public static final int SIZE_UNKNOWN = -1;
41
42     @SuppressWarnings("unused")
43     private static final String TAG = "TileImageView";
44
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;
51
52     private static BitmapPool sTilePool;
53
54     /*
55      *  This is the tile state in the CPU side.
56      *  Life of a Tile:
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()
70      */
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;
78
79     private Model mModel;
80     private ScreenNail mScreenNail;
81     protected int mLevelCount;  // cache the value of mScaledBitmaps.length
82
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;
90
91     // The offsets of the (left, top) of the upper-left tile to the (left, top)
92     // of the view.
93     private int mOffsetX;
94     private int mOffsetY;
95
96     private int mUploadQuota;
97     private boolean mRenderComplete;
98
99     private final RectF mSourceRect = new RectF();
100     private final RectF mTargetRect = new RectF();
101
102     private final LongSparseArray<Tile> mActiveTiles = new LongSparseArray<Tile>();
103
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();
108
109     // The width and height of the full-sized bitmap
110     protected int mImageWidth = SIZE_UNKNOWN;
111     protected int mImageHeight = SIZE_UNKNOWN;
112
113     protected int mCenterX;
114     protected int mCenterY;
115     protected float mScale;
116     protected int mRotation;
117
118     // Temp variables to avoid memory allocation
119     private final Rect mTileRange = new Rect();
120     private final Rect mActiveRange[] = {new Rect(), new Rect()};
121
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;
127
128     public static interface Model {
129         public int getLevelCount();
130         public ScreenNail getScreenNail();
131         public int getImageWidth();
132         public int getImageHeight();
133
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.
140         //
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.
144         //
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);
148     }
149
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())) {
155                 TILE_SIZE = 510 ;
156             } else {
157                 TILE_SIZE = 254;
158             }
159             BITMAP_SIZE = TILE_SIZE + TILE_BORDER * 2;
160             sTilePool =
161                     ApiHelper.HAS_REUSING_BITMAP_IN_BITMAP_REGION_DECODER
162                     ? new BitmapPool(BITMAP_SIZE, BITMAP_SIZE, 128)
163                     : null;
164         }
165     }
166
167     public void setModel(Model model) {
168         mModel = model;
169         if (model != null) notifyModelInvalidated();
170     }
171
172     public void setScreenNail(ScreenNail s) {
173         mScreenNail = s;
174     }
175
176     public void notifyModelInvalidated() {
177         invalidateTiles();
178         if (mModel == null) {
179             mScreenNail = null;
180             mImageWidth = 0;
181             mImageHeight = 0;
182             mLevelCount = 0;
183         } else {
184             setScreenNail(mModel.getScreenNail());
185             mImageWidth = mModel.getImageWidth();
186             mImageHeight = mModel.getImageHeight();
187             mLevelCount = mModel.getLevelCount();
188         }
189         layoutTiles(mCenterX, mCenterY, mScale, mRotation);
190         invalidate();
191     }
192
193     @Override
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);
198     }
199
200     // Prepare the tiles we want to use for display.
201     //
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();
211
212         // The tile levels we want to keep as texture is in the range
213         // [fromLevel, endLevel).
214         int fromLevel;
215         int endLevel;
216
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);
219
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;
229         } else {
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);
234         }
235
236         fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2));
237         endLevel = Math.min(fromLevel + 2, mLevelCount);
238
239         Rect range[] = mActiveRange;
240         for (int i = fromLevel; i < endLevel; ++i) {
241             getRange(range[i - fromLevel], centerX, centerY, i, rotation);
242         }
243
244         // If rotation is transient, don't update the tile.
245         if (rotation % 90 != 0) return;
246
247         synchronized (this) {
248             mDecodeQueue.clean();
249             mUploadQueue.clean();
250             mBackgroundTileUploaded = false;
251
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);
261                     i--;
262                     n--;
263                     recycleTile(tile);
264                 }
265             }
266         }
267
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);
274                 }
275             }
276         }
277         invalidate();
278     }
279
280     protected synchronized void invalidateTiles() {
281         mDecodeQueue.clean();
282         mUploadQueue.clean();
283
284         // TODO disable decoder
285         int n = mActiveTiles.size();
286         for (int i = 0; i < n; i++) {
287             Tile tile = mActiveTiles.valueAt(i);
288             recycleTile(tile);
289         }
290         mActiveTiles.clear();
291     }
292
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);
295     }
296
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.
300     //
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) {
305
306         double radians = Math.toRadians(-rotation);
307         double w = getWidth();
308         double h = getHeight();
309
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)));
316
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);
321
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);
328
329         out.set(left, top, right, bottom);
330     }
331
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();
337
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)
341         int distW, distH;
342         if (mRotation % 180 == 0) {
343             distW = mImageWidth / 2 - mCenterX;
344             distH = mImageHeight / 2 - mCenterY;
345         } else {
346             distW = mImageHeight / 2 - mCenterY;
347             distH = mImageWidth / 2 - mCenterX;
348         }
349
350         // Convert to view coordinates. mScale translates from bitmap units to
351         // view units.
352         center.x = Math.round(viewW / 2f + distW * mScale);
353         center.y = Math.round(viewH / 2f + distH * mScale);
354     }
355
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;
359         mCenterX = centerX;
360         mCenterY = centerY;
361         mScale = scale;
362         mRotation = rotation;
363         layoutTiles(centerX, centerY, scale, rotation);
364         invalidate();
365         return true;
366     }
367
368     public void freeTextures() {
369         mIsTextureFreed = true;
370
371         if (mTileDecoder != null) {
372             mTileDecoder.cancel();
373             mTileDecoder.get();
374             mTileDecoder = null;
375         }
376
377         int n = mActiveTiles.size();
378         for (int i = 0; i < n; i++) {
379             Tile texture = mActiveTiles.valueAt(i);
380             texture.recycle();
381         }
382         mActiveTiles.clear();
383         mTileRange.set(0, 0, 0, 0);
384
385         synchronized (this) {
386             mUploadQueue.clean();
387             mDecodeQueue.clean();
388             Tile tile = mRecycledQueue.pop();
389             while (tile != null) {
390                 tile.recycle();
391                 tile = mRecycledQueue.pop();
392             }
393         }
394         setScreenNail(null);
395         if (sTilePool != null) sTilePool.clear();
396     }
397
398     public void prepareTextures() {
399         if (mTileDecoder == null) {
400             mTileDecoder = mThreadPool.submit(new TileDecoder());
401         }
402         if (mIsTextureFreed) {
403             layoutTiles(mCenterX, mCenterY, mScale, mRotation);
404             mIsTextureFreed = false;
405             setScreenNail(mModel == null ? null : mModel.getScreenNail());
406         }
407     }
408
409     @Override
410     protected void render(GLCanvas canvas) {
411         mUploadQuota = UPLOAD_LIMIT;
412         mRenderComplete = true;
413
414         int level = mLevel;
415         int rotation = mRotation;
416         int flags = 0;
417         if (rotation != 0) flags |= GLCanvas.SAVE_FLAG_MATRIX;
418
419         if (flags != 0) {
420             canvas.save(flags);
421             if (rotation != 0) {
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);
426             }
427         }
428         try {
429             if (level != mLevelCount && !isScreenNailAnimating()) {
430                 if (mScreenNail != null) {
431                     mScreenNail.noDraw();
432                 }
433
434                 int size = (TILE_SIZE << level);
435                 float length = size * mScale;
436                 Rect r = mTileRange;
437
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);
443                     }
444                 }
445             } else if (mScreenNail != null) {
446                 mScreenNail.draw(canvas, mOffsetX, mOffsetY,
447                         Math.round(mImageWidth * mScale),
448                         Math.round(mImageHeight * mScale));
449                 if (isScreenNailAnimating()) {
450                     invalidate();
451                 }
452             }
453         } finally {
454             if (flags != 0) canvas.restore();
455         }
456
457         if (mRenderComplete) {
458             if (!mBackgroundTileUploaded) uploadBackgroundTiles(canvas);
459         } else {
460             invalidate();
461         }
462     }
463
464     private boolean isScreenNailAnimating() {
465         return (mScreenNail instanceof TiledScreenNail)
466                 && ((TiledScreenNail) mScreenNail).isAnimating();
467     }
468
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);
475         }
476     }
477
478     void queueForUpload(Tile tile) {
479         synchronized (this) {
480             mUploadQueue.push(tile);
481         }
482         if (mTileUploader.mActive.compareAndSet(false, true)) {
483             getGLRoot().addOnGLIdleListener(mTileUploader);
484         }
485     }
486
487     synchronized void queueForDecode(Tile tile) {
488         if (tile.mTileState == STATE_ACTIVATED) {
489             tile.mTileState = STATE_IN_QUEUE;
490             if (mDecodeQueue.push(tile)) notifyAll();
491         }
492     }
493
494     boolean decodeTile(Tile tile) {
495         synchronized (this) {
496             if (tile.mTileState != STATE_IN_QUEUE) return false;
497             tile.mTileState = STATE_DECODING;
498         }
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;
506                 }
507                 mRecycledQueue.push(tile);
508                 return false;
509             }
510             tile.mTileState = decodeComplete ? STATE_DECODED : STATE_DECODE_FAIL;
511             return decodeComplete;
512         }
513     }
514
515     private synchronized Tile obtainTile(int x, int y, int level) {
516         Tile tile = mRecycledQueue.pop();
517         if (tile != null) {
518             tile.mTileState = STATE_ACTIVATED;
519             tile.update(x, y, level);
520             return tile;
521         }
522         return new Tile(x, y, level);
523     }
524
525     synchronized void recycleTile(Tile tile) {
526         if (tile.mTileState == STATE_DECODING) {
527             tile.mTileState = STATE_RECYCLING;
528             return;
529         }
530         tile.mTileState = STATE_RECYCLED;
531         if (tile.mDecodedTile != null) {
532             if (sTilePool != null) sTilePool.recycle(tile.mDecodedTile);
533             tile.mDecodedTile = null;
534         }
535         mRecycledQueue.push(tile);
536     }
537
538     private void activateTile(int x, int y, int level) {
539         long key = makeTileKey(x, y, level);
540         Tile tile = mActiveTiles.get(key);
541         if (tile != null) {
542             if (tile.mTileState == STATE_IN_QUEUE) {
543                 tile.mTileState = STATE_ACTIVATED;
544             }
545             return;
546         }
547         tile = obtainTile(x, y, level);
548         mActiveTiles.put(key, tile);
549     }
550
551     private Tile getTile(int x, int y, int level) {
552         return mActiveTiles.get(makeTileKey(x, y, level));
553     }
554
555     private static long makeTileKey(int x, int y, int level) {
556         long result = x;
557         result = (result << 16) | y;
558         result = (result << 16) | level;
559         return result;
560     }
561
562     private class TileUploader implements GLRoot.OnGLIdleListener {
563         AtomicBoolean mActive = new AtomicBoolean(false);
564
565         @Override
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;
571             Tile tile = null;
572             while (quota > 0) {
573                 synchronized (TileImageView.this) {
574                     tile = mUploadQueue.pop();
575                 }
576                 if (tile == null) break;
577                 if (!tile.isContentValid()) {
578                     boolean hasBeenLoaded = tile.isLoaded();
579                     Utils.assertTrue(tile.mTileState == STATE_DECODED);
580                     tile.updateContent(canvas);
581                     if (!hasBeenLoaded) tile.draw(canvas, 0, 0);
582                     --quota;
583                 }
584             }
585             if (tile == null) mActive.set(false);
586             return tile != null;
587         }
588     }
589
590     // Draw the tile to a square at canvas that locates at (x, y) and
591     // has a side length of length.
592     public void drawTile(GLCanvas canvas,
593             int tx, int ty, int level, float x, float y, float length) {
594         RectF source = mSourceRect;
595         RectF target = mTargetRect;
596         target.set(x, y, x + length, y + length);
597         source.set(0, 0, TILE_SIZE, TILE_SIZE);
598
599         Tile tile = getTile(tx, ty, level);
600         if (tile != null) {
601             if (!tile.isContentValid()) {
602                 if (tile.mTileState == STATE_DECODED) {
603                     if (mUploadQuota > 0) {
604                         --mUploadQuota;
605                         tile.updateContent(canvas);
606                     } else {
607                         mRenderComplete = false;
608                     }
609                 } else if (tile.mTileState != STATE_DECODE_FAIL){
610                     mRenderComplete = false;
611                     queueForDecode(tile);
612                 }
613             }
614             if (drawTile(tile, canvas, source, target)) return;
615         }
616         if (mScreenNail != null) {
617             int size = TILE_SIZE << level;
618             float scaleX = (float) mScreenNail.getWidth() / mImageWidth;
619             float scaleY = (float) mScreenNail.getHeight() / mImageHeight;
620             source.set(tx * scaleX, ty * scaleY, (tx + size) * scaleX,
621                     (ty + size) * scaleY);
622             mScreenNail.draw(canvas, source, target);
623         }
624     }
625
626     static boolean drawTile(
627             Tile tile, GLCanvas canvas, RectF source, RectF target) {
628         while (true) {
629             if (tile.isContentValid()) {
630                 // offset source rectangle for the texture border.
631                 source.offset(TILE_BORDER, TILE_BORDER);
632                 canvas.drawTexture(tile, source, target);
633                 return true;
634             }
635
636             // Parent can be divided to four quads and tile is one of the four.
637             Tile parent = tile.getParentTile();
638             if (parent == null) return false;
639             if (tile.mX == parent.mX) {
640                 source.left /= 2f;
641                 source.right /= 2f;
642             } else {
643                 source.left = (TILE_SIZE + source.left) / 2f;
644                 source.right = (TILE_SIZE + source.right) / 2f;
645             }
646             if (tile.mY == parent.mY) {
647                 source.top /= 2f;
648                 source.bottom /= 2f;
649             } else {
650                 source.top = (TILE_SIZE + source.top) / 2f;
651                 source.bottom = (TILE_SIZE + source.bottom) / 2f;
652             }
653             tile = parent;
654         }
655     }
656
657     private class Tile extends UploadedTexture {
658         public int mX;
659         public int mY;
660         public int mTileLevel;
661         public Tile mNext;
662         public Bitmap mDecodedTile;
663         public volatile int mTileState = STATE_ACTIVATED;
664
665         public Tile(int x, int y, int level) {
666             mX = x;
667             mY = y;
668             mTileLevel = level;
669         }
670
671         @Override
672         protected void onFreeBitmap(Bitmap bitmap) {
673             if (sTilePool != null) sTilePool.recycle(bitmap);
674         }
675
676         boolean decode() {
677             // Get a tile from the original image. The tile is down-scaled
678             // by (1 << mTilelevel) from a region in the original image.
679             try {
680                 mDecodedTile = DecodeUtils.ensureGLCompatibleBitmap(mModel.getTile(
681                         mTileLevel, mX, mY, TILE_SIZE, TILE_BORDER, sTilePool));
682             } catch (Throwable t) {
683                 Log.w(TAG, "fail to decode tile", t);
684             }
685             return mDecodedTile != null;
686         }
687
688         @Override
689         protected Bitmap onGetBitmap() {
690             Utils.assertTrue(mTileState == STATE_DECODED);
691
692             // We need to override the width and height, so that we won't
693             // draw beyond the boundaries.
694             int rightEdge = ((mImageWidth - mX) >> mTileLevel) + TILE_BORDER;
695             int bottomEdge = ((mImageHeight - mY) >> mTileLevel) + TILE_BORDER;
696             setSize(Math.min(BITMAP_SIZE, rightEdge), Math.min(BITMAP_SIZE, bottomEdge));
697
698             Bitmap bitmap = mDecodedTile;
699             mDecodedTile = null;
700             mTileState = STATE_ACTIVATED;
701             return bitmap;
702         }
703
704         // We override getTextureWidth() and getTextureHeight() here, so the
705         // texture can be re-used for different tiles regardless of the actual
706         // size of the tile (which may be small because it is a tile at the
707         // boundary).
708         @Override
709         public int getTextureWidth() {
710             return TILE_SIZE + TILE_BORDER * 2;
711         }
712
713         @Override
714         public int getTextureHeight() {
715             return TILE_SIZE + TILE_BORDER * 2;
716         }
717
718         public void update(int x, int y, int level) {
719             mX = x;
720             mY = y;
721             mTileLevel = level;
722             invalidateContent();
723         }
724
725         public Tile getParentTile() {
726             if (mTileLevel + 1 == mLevelCount) return null;
727             int size = TILE_SIZE << (mTileLevel + 1);
728             int x = size * (mX / size);
729             int y = size * (mY / size);
730             return getTile(x, y, mTileLevel + 1);
731         }
732
733         @Override
734         public String toString() {
735             return String.format("tile(%s, %s, %s / %s)",
736                     mX / TILE_SIZE, mY / TILE_SIZE, mLevel, mLevelCount);
737         }
738     }
739
740     private static class TileQueue {
741         private Tile mHead;
742
743         public Tile pop() {
744             Tile tile = mHead;
745             if (tile != null) mHead = tile.mNext;
746             return tile;
747         }
748
749         public boolean push(Tile tile) {
750             boolean wasEmpty = mHead == null;
751             tile.mNext = mHead;
752             mHead = tile;
753             return wasEmpty;
754         }
755
756         public void clean() {
757             mHead = null;
758         }
759     }
760
761     private class TileDecoder implements ThreadPool.Job<Void> {
762
763         private CancelListener mNotifier = new CancelListener() {
764             @Override
765             public void onCancel() {
766                 synchronized (TileImageView.this) {
767                     TileImageView.this.notifyAll();
768                 }
769             }
770         };
771
772         @Override
773         public Void run(JobContext jc) {
774             jc.setMode(ThreadPool.MODE_NONE);
775             jc.setCancelListener(mNotifier);
776             while (!jc.isCancelled()) {
777                 Tile tile = null;
778                 synchronized(TileImageView.this) {
779                     tile = mDecodeQueue.pop();
780                     if (tile == null && !jc.isCancelled()) {
781                         Utils.waitWithoutInterrupt(TileImageView.this);
782                     }
783                 }
784                 if (tile == null) continue;
785                 if (decodeTile(tile)) queueForUpload(tile);
786             }
787             return null;
788         }
789     }
790 }