OSDN Git Service

Merge "Move LightCycle undo to settings area." into gb-ub-photos-arches
[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 BitmapScreenNail)
466                 && ((BitmapScreenNail) 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                     Utils.assertTrue(tile.mTileState == STATE_DECODED);
579                     tile.updateContent(canvas);
580                     --quota;
581                 }
582             }
583             if (tile == null) mActive.set(false);
584             return tile != null;
585         }
586     }
587
588     // Draw the tile to a square at canvas that locates at (x, y) and
589     // has a side length of length.
590     public void drawTile(GLCanvas canvas,
591             int tx, int ty, int level, float x, float y, float length) {
592         RectF source = mSourceRect;
593         RectF target = mTargetRect;
594         target.set(x, y, x + length, y + length);
595         source.set(0, 0, TILE_SIZE, TILE_SIZE);
596
597         Tile tile = getTile(tx, ty, level);
598         if (tile != null) {
599             if (!tile.isContentValid()) {
600                 if (tile.mTileState == STATE_DECODED) {
601                     if (mUploadQuota > 0) {
602                         --mUploadQuota;
603                         tile.updateContent(canvas);
604                     } else {
605                         mRenderComplete = false;
606                     }
607                 } else if (tile.mTileState != STATE_DECODE_FAIL){
608                     mRenderComplete = false;
609                     queueForDecode(tile);
610                 }
611             }
612             if (drawTile(tile, canvas, source, target)) return;
613         }
614         if (mScreenNail != null) {
615             int size = TILE_SIZE << level;
616             float scaleX = (float) mScreenNail.getWidth() / mImageWidth;
617             float scaleY = (float) mScreenNail.getHeight() / mImageHeight;
618             source.set(tx * scaleX, ty * scaleY, (tx + size) * scaleX,
619                     (ty + size) * scaleY);
620             mScreenNail.draw(canvas, source, target);
621         }
622     }
623
624     // TODO: avoid drawing the unused part of the textures.
625     static boolean drawTile(
626             Tile tile, GLCanvas canvas, RectF source, RectF target) {
627         while (true) {
628             if (tile.isContentValid()) {
629                 // offset source rectangle for the texture border.
630                 source.offset(TILE_BORDER, TILE_BORDER);
631                 canvas.drawTexture(tile, source, target);
632                 return true;
633             }
634
635             // Parent can be divided to four quads and tile is one of the four.
636             Tile parent = tile.getParentTile();
637             if (parent == null) return false;
638             if (tile.mX == parent.mX) {
639                 source.left /= 2f;
640                 source.right /= 2f;
641             } else {
642                 source.left = (TILE_SIZE + source.left) / 2f;
643                 source.right = (TILE_SIZE + source.right) / 2f;
644             }
645             if (tile.mY == parent.mY) {
646                 source.top /= 2f;
647                 source.bottom /= 2f;
648             } else {
649                 source.top = (TILE_SIZE + source.top) / 2f;
650                 source.bottom = (TILE_SIZE + source.bottom) / 2f;
651             }
652             tile = parent;
653         }
654     }
655
656     private class Tile extends UploadedTexture {
657         public int mX;
658         public int mY;
659         public int mTileLevel;
660         public Tile mNext;
661         public Bitmap mDecodedTile;
662         public volatile int mTileState = STATE_ACTIVATED;
663
664         public Tile(int x, int y, int level) {
665             mX = x;
666             mY = y;
667             mTileLevel = level;
668         }
669
670         @Override
671         protected void onFreeBitmap(Bitmap bitmap) {
672             if (sTilePool != null) sTilePool.recycle(bitmap);
673         }
674
675         boolean decode() {
676             // Get a tile from the original image. The tile is down-scaled
677             // by (1 << mTilelevel) from a region in the original image.
678             try {
679                 mDecodedTile = DecodeUtils.ensureGLCompatibleBitmap(mModel.getTile(
680                         mTileLevel, mX, mY, TILE_SIZE, TILE_BORDER, sTilePool));
681             } catch (Throwable t) {
682                 Log.w(TAG, "fail to decode tile", t);
683             }
684             return mDecodedTile != null;
685         }
686
687         @Override
688         protected Bitmap onGetBitmap() {
689             Utils.assertTrue(mTileState == STATE_DECODED);
690
691             // We need to override the width and height, so that we won't
692             // draw beyond the boundaries.
693             int rightEdge = ((mImageWidth - mX) >> mTileLevel) + TILE_BORDER;
694             int bottomEdge = ((mImageHeight - mY) >> mTileLevel) + TILE_BORDER;
695             setSize(Math.min(BITMAP_SIZE, rightEdge), Math.min(BITMAP_SIZE, bottomEdge));
696
697             Bitmap bitmap = mDecodedTile;
698             mDecodedTile = null;
699             mTileState = STATE_ACTIVATED;
700             return bitmap;
701         }
702
703         // We override getTextureWidth() and getTextureHeight() here, so the
704         // texture can be re-used for different tiles regardless of the actual
705         // size of the tile (which may be small because it is a tile at the
706         // boundary).
707         @Override
708         public int getTextureWidth() {
709             return TILE_SIZE + TILE_BORDER * 2;
710         }
711
712         @Override
713         public int getTextureHeight() {
714             return TILE_SIZE + TILE_BORDER * 2;
715         }
716
717         public void update(int x, int y, int level) {
718             mX = x;
719             mY = y;
720             mTileLevel = level;
721             invalidateContent();
722         }
723
724         public Tile getParentTile() {
725             if (mTileLevel + 1 == mLevelCount) return null;
726             int size = TILE_SIZE << (mTileLevel + 1);
727             int x = size * (mX / size);
728             int y = size * (mY / size);
729             return getTile(x, y, mTileLevel + 1);
730         }
731
732         @Override
733         public String toString() {
734             return String.format("tile(%s, %s, %s / %s)",
735                     mX / TILE_SIZE, mY / TILE_SIZE, mLevel, mLevelCount);
736         }
737     }
738
739     private static class TileQueue {
740         private Tile mHead;
741
742         public Tile pop() {
743             Tile tile = mHead;
744             if (tile != null) mHead = tile.mNext;
745             return tile;
746         }
747
748         public boolean push(Tile tile) {
749             boolean wasEmpty = mHead == null;
750             tile.mNext = mHead;
751             mHead = tile;
752             return wasEmpty;
753         }
754
755         public void clean() {
756             mHead = null;
757         }
758     }
759
760     private class TileDecoder implements ThreadPool.Job<Void> {
761
762         private CancelListener mNotifier = new CancelListener() {
763             @Override
764             public void onCancel() {
765                 synchronized (TileImageView.this) {
766                     TileImageView.this.notifyAll();
767                 }
768             }
769         };
770
771         @Override
772         public Void run(JobContext jc) {
773             jc.setMode(ThreadPool.MODE_NONE);
774             jc.setCancelListener(mNotifier);
775             while (!jc.isCancelled()) {
776                 Tile tile = null;
777                 synchronized(TileImageView.this) {
778                     tile = mDecodeQueue.pop();
779                     if (tile == null && !jc.isCancelled()) {
780                         Utils.waitWithoutInterrupt(TileImageView.this);
781                     }
782                 }
783                 if (tile == null) continue;
784                 if (decodeTile(tile)) queueForUpload(tile);
785             }
786             return null;
787         }
788     }
789 }