OSDN Git Service

Merge "ExifModifier" 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.content.Context;
20 import android.graphics.Bitmap;
21 import android.graphics.Point;
22 import android.graphics.Rect;
23 import android.graphics.RectF;
24 import android.support.v4.util.LongSparseArray;
25 import android.util.DisplayMetrics;
26 import android.util.FloatMath;
27 import android.view.WindowManager;
28
29 import com.android.gallery3d.app.GalleryContext;
30 import com.android.gallery3d.common.ApiHelper;
31 import com.android.gallery3d.common.Utils;
32 import com.android.gallery3d.data.BitmapPool;
33 import com.android.gallery3d.data.DecodeUtils;
34 import com.android.gallery3d.glrenderer.GLCanvas;
35 import com.android.gallery3d.glrenderer.UploadedTexture;
36 import com.android.gallery3d.util.Future;
37 import com.android.gallery3d.util.ThreadPool;
38 import com.android.gallery3d.util.ThreadPool.CancelListener;
39 import com.android.gallery3d.util.ThreadPool.JobContext;
40
41 import java.util.concurrent.atomic.AtomicBoolean;
42
43 public class TileImageView extends GLView {
44     public static final int SIZE_UNKNOWN = -1;
45
46     @SuppressWarnings("unused")
47     private static final String TAG = "TileImageView";
48     private static final int UPLOAD_LIMIT = 1;
49
50     // TILE_SIZE must be 2^N
51     private static int sTileSize;
52
53     private static BitmapPool sTilePool;
54
55     /*
56      *  This is the tile state in the CPU side.
57      *  Life of a Tile:
58      *      ACTIVATED (initial state)
59      *              --> IN_QUEUE - by queueForDecode()
60      *              --> RECYCLED - by recycleTile()
61      *      IN_QUEUE --> DECODING - by decodeTile()
62      *               --> RECYCLED - by recycleTile)
63      *      DECODING --> RECYCLING - by recycleTile()
64      *               --> DECODED  - by decodeTile()
65      *               --> DECODE_FAIL - by decodeTile()
66      *      RECYCLING --> RECYCLED - by decodeTile()
67      *      DECODED --> ACTIVATED - (after the decoded bitmap is uploaded)
68      *      DECODED --> RECYCLED - by recycleTile()
69      *      DECODE_FAIL -> RECYCLED - by recycleTile()
70      *      RECYCLED --> ACTIVATED - by obtainTile()
71      */
72     private static final int STATE_ACTIVATED = 0x01;
73     private static final int STATE_IN_QUEUE = 0x02;
74     private static final int STATE_DECODING = 0x04;
75     private static final int STATE_DECODED = 0x08;
76     private static final int STATE_DECODE_FAIL = 0x10;
77     private static final int STATE_RECYCLING = 0x20;
78     private static final int STATE_RECYCLED = 0x40;
79
80     private TileSource mModel;
81     private ScreenNail mScreenNail;
82     protected int mLevelCount;  // cache the value of mScaledBitmaps.length
83
84     // The mLevel variable indicates which level of bitmap we should use.
85     // Level 0 means the original full-sized bitmap, and a larger value means
86     // a smaller scaled bitmap (The width and height of each scaled bitmap is
87     // half size of the previous one). If the value is in [0, mLevelCount), we
88     // use the bitmap in mScaledBitmaps[mLevel] for display, otherwise the value
89     // is mLevelCount, and that means we use mScreenNail for display.
90     private int mLevel = 0;
91
92     // The offsets of the (left, top) of the upper-left tile to the (left, top)
93     // of the view.
94     private int mOffsetX;
95     private int mOffsetY;
96
97     private int mUploadQuota;
98     private boolean mRenderComplete;
99
100     private final RectF mSourceRect = new RectF();
101     private final RectF mTargetRect = new RectF();
102
103     private final LongSparseArray<Tile> mActiveTiles = new LongSparseArray<Tile>();
104
105     // The following three queue is guarded by TileImageView.this
106     private final TileQueue mRecycledQueue = new TileQueue();
107     private final TileQueue mUploadQueue = new TileQueue();
108     private final TileQueue mDecodeQueue = new TileQueue();
109
110     // The width and height of the full-sized bitmap
111     protected int mImageWidth = SIZE_UNKNOWN;
112     protected int mImageHeight = SIZE_UNKNOWN;
113
114     protected int mCenterX;
115     protected int mCenterY;
116     protected float mScale;
117     protected int mRotation;
118
119     // Temp variables to avoid memory allocation
120     private final Rect mTileRange = new Rect();
121     private final Rect mActiveRange[] = {new Rect(), new Rect()};
122
123     private final TileUploader mTileUploader = new TileUploader();
124     private boolean mIsTextureFreed;
125     private Future<Void> mTileDecoder;
126     private final ThreadPool mThreadPool;
127     private boolean mBackgroundTileUploaded;
128
129     public static interface TileSource {
130         public int getLevelCount();
131         public ScreenNail getScreenNail();
132         public int getImageWidth();
133         public int getImageHeight();
134
135         // The tile returned by this method can be specified this way: Assuming
136         // the image size is (width, height), first take the intersection of (0,
137         // 0) - (width, height) and (x, y) - (x + tileSize, y + tileSize). If
138         // in extending the region, we found some part of the region are outside
139         // the image, those pixels are filled with black.
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                 BitmapPool pool);
148     }
149
150     public static boolean isHighResolution(Context context) {
151         DisplayMetrics metrics = new DisplayMetrics();
152         WindowManager wm = (WindowManager)
153                 context.getSystemService(Context.WINDOW_SERVICE);
154         wm.getDefaultDisplay().getMetrics(metrics);
155         return metrics.heightPixels > 2048 ||  metrics.widthPixels > 2048;
156     }
157
158     public TileImageView(GalleryContext context) {
159         mThreadPool = context.getThreadPool();
160         mTileDecoder = mThreadPool.submit(new TileDecoder());
161         if (sTileSize == 0) {
162             if (isHighResolution(context.getAndroidContext())) {
163                 sTileSize = 512 ;
164             } else {
165                 sTileSize = 256;
166             }
167             sTilePool =
168                     ApiHelper.HAS_REUSING_BITMAP_IN_BITMAP_REGION_DECODER
169                     ? new BitmapPool(sTileSize, sTileSize, 128)
170                     : null;
171         }
172     }
173
174     public void setModel(TileSource model) {
175         mModel = model;
176         if (model != null) notifyModelInvalidated();
177     }
178
179     public void setScreenNail(ScreenNail s) {
180         mScreenNail = s;
181     }
182
183     public void notifyModelInvalidated() {
184         invalidateTiles();
185         if (mModel == null) {
186             mScreenNail = null;
187             mImageWidth = 0;
188             mImageHeight = 0;
189             mLevelCount = 0;
190         } else {
191             setScreenNail(mModel.getScreenNail());
192             mImageWidth = mModel.getImageWidth();
193             mImageHeight = mModel.getImageHeight();
194             mLevelCount = mModel.getLevelCount();
195         }
196         layoutTiles(mCenterX, mCenterY, mScale, mRotation);
197         invalidate();
198     }
199
200     @Override
201     protected void onLayout(
202             boolean changeSize, int left, int top, int right, int bottom) {
203         super.onLayout(changeSize, left, top, right, bottom);
204         if (changeSize) layoutTiles(mCenterX, mCenterY, mScale, mRotation);
205     }
206
207     // Prepare the tiles we want to use for display.
208     //
209     // 1. Decide the tile level we want to use for display.
210     // 2. Decide the tile levels we want to keep as texture (in addition to
211     //    the one we use for display).
212     // 3. Recycle unused tiles.
213     // 4. Activate the tiles we want.
214     private void layoutTiles(int centerX, int centerY, float scale, int rotation) {
215         // The width and height of this view.
216         int width = getWidth();
217         int height = getHeight();
218
219         // The tile levels we want to keep as texture is in the range
220         // [fromLevel, endLevel).
221         int fromLevel;
222         int endLevel;
223
224         // We want to use a texture larger than or equal to the display size.
225         mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount);
226
227         // We want to keep one more tile level as texture in addition to what
228         // we use for display. So it can be faster when the scale moves to the
229         // next level. We choose a level closer to the current scale.
230         if (mLevel != mLevelCount) {
231             Rect range = mTileRange;
232             getRange(range, centerX, centerY, mLevel, scale, rotation);
233             mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale);
234             mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale);
235             fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel;
236         } else {
237             // Activate the tiles of the smallest two levels.
238             fromLevel = mLevel - 2;
239             mOffsetX = Math.round(width / 2f - centerX * scale);
240             mOffsetY = Math.round(height / 2f - centerY * scale);
241         }
242
243         fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2));
244         endLevel = Math.min(fromLevel + 2, mLevelCount);
245
246         Rect range[] = mActiveRange;
247         for (int i = fromLevel; i < endLevel; ++i) {
248             getRange(range[i - fromLevel], centerX, centerY, i, rotation);
249         }
250
251         // If rotation is transient, don't update the tile.
252         if (rotation % 90 != 0) return;
253
254         synchronized (this) {
255             mDecodeQueue.clean();
256             mUploadQueue.clean();
257             mBackgroundTileUploaded = false;
258
259             // Recycle unused tiles: if the level of the active tile is outside the
260             // range [fromLevel, endLevel) or not in the visible range.
261             int n = mActiveTiles.size();
262             for (int i = 0; i < n; i++) {
263                 Tile tile = mActiveTiles.valueAt(i);
264                 int level = tile.mTileLevel;
265                 if (level < fromLevel || level >= endLevel
266                         || !range[level - fromLevel].contains(tile.mX, tile.mY)) {
267                     mActiveTiles.removeAt(i);
268                     i--;
269                     n--;
270                     recycleTile(tile);
271                 }
272             }
273         }
274
275         for (int i = fromLevel; i < endLevel; ++i) {
276             int size = sTileSize << i;
277             Rect r = range[i - fromLevel];
278             for (int y = r.top, bottom = r.bottom; y < bottom; y += size) {
279                 for (int x = r.left, right = r.right; x < right; x += size) {
280                     activateTile(x, y, i);
281                 }
282             }
283         }
284         invalidate();
285     }
286
287     protected synchronized void invalidateTiles() {
288         mDecodeQueue.clean();
289         mUploadQueue.clean();
290
291         // TODO disable decoder
292         int n = mActiveTiles.size();
293         for (int i = 0; i < n; i++) {
294             Tile tile = mActiveTiles.valueAt(i);
295             recycleTile(tile);
296         }
297         mActiveTiles.clear();
298     }
299
300     private void getRange(Rect out, int cX, int cY, int level, int rotation) {
301         getRange(out, cX, cY, level, 1f / (1 << (level + 1)), rotation);
302     }
303
304     // If the bitmap is scaled by the given factor "scale", return the
305     // rectangle containing visible range. The left-top coordinate returned is
306     // aligned to the tile boundary.
307     //
308     // (cX, cY) is the point on the original bitmap which will be put in the
309     // center of the ImageViewer.
310     private void getRange(Rect out,
311             int cX, int cY, int level, float scale, int rotation) {
312
313         double radians = Math.toRadians(-rotation);
314         double w = getWidth();
315         double h = getHeight();
316
317         double cos = Math.cos(radians);
318         double sin = Math.sin(radians);
319         int width = (int) Math.ceil(Math.max(
320                 Math.abs(cos * w - sin * h), Math.abs(cos * w + sin * h)));
321         int height = (int) Math.ceil(Math.max(
322                 Math.abs(sin * w + cos * h), Math.abs(sin * w - cos * h)));
323
324         int left = (int) FloatMath.floor(cX - width / (2f * scale));
325         int top = (int) FloatMath.floor(cY - height / (2f * scale));
326         int right = (int) FloatMath.ceil(left + width / scale);
327         int bottom = (int) FloatMath.ceil(top + height / scale);
328
329         // align the rectangle to tile boundary
330         int size = sTileSize << level;
331         left = Math.max(0, size * (left / size));
332         top = Math.max(0, size * (top / size));
333         right = Math.min(mImageWidth, right);
334         bottom = Math.min(mImageHeight, bottom);
335
336         out.set(left, top, right, bottom);
337     }
338
339     // Calculate where the center of the image is, in the view coordinates.
340     public void getImageCenter(Point center) {
341         // The width and height of this view.
342         int viewW = getWidth();
343         int viewH = getHeight();
344
345         // The distance between the center of the view to the center of the
346         // bitmap, in bitmap units. (mCenterX and mCenterY are the bitmap
347         // coordinates correspond to the center of view)
348         int distW, distH;
349         if (mRotation % 180 == 0) {
350             distW = mImageWidth / 2 - mCenterX;
351             distH = mImageHeight / 2 - mCenterY;
352         } else {
353             distW = mImageHeight / 2 - mCenterY;
354             distH = mImageWidth / 2 - mCenterX;
355         }
356
357         // Convert to view coordinates. mScale translates from bitmap units to
358         // view units.
359         center.x = Math.round(viewW / 2f + distW * mScale);
360         center.y = Math.round(viewH / 2f + distH * mScale);
361     }
362
363     public boolean setPosition(int centerX, int centerY, float scale, int rotation) {
364         if (mCenterX == centerX && mCenterY == centerY
365                 && mScale == scale && mRotation == rotation) return false;
366         mCenterX = centerX;
367         mCenterY = centerY;
368         mScale = scale;
369         mRotation = rotation;
370         layoutTiles(centerX, centerY, scale, rotation);
371         invalidate();
372         return true;
373     }
374
375     public void freeTextures() {
376         mIsTextureFreed = true;
377
378         if (mTileDecoder != null) {
379             mTileDecoder.cancel();
380             mTileDecoder.get();
381             mTileDecoder = null;
382         }
383
384         int n = mActiveTiles.size();
385         for (int i = 0; i < n; i++) {
386             Tile texture = mActiveTiles.valueAt(i);
387             texture.recycle();
388         }
389         mActiveTiles.clear();
390         mTileRange.set(0, 0, 0, 0);
391
392         synchronized (this) {
393             mUploadQueue.clean();
394             mDecodeQueue.clean();
395             Tile tile = mRecycledQueue.pop();
396             while (tile != null) {
397                 tile.recycle();
398                 tile = mRecycledQueue.pop();
399             }
400         }
401         setScreenNail(null);
402         if (sTilePool != null) sTilePool.clear();
403     }
404
405     public void prepareTextures() {
406         if (mTileDecoder == null) {
407             mTileDecoder = mThreadPool.submit(new TileDecoder());
408         }
409         if (mIsTextureFreed) {
410             layoutTiles(mCenterX, mCenterY, mScale, mRotation);
411             mIsTextureFreed = false;
412             setScreenNail(mModel == null ? null : mModel.getScreenNail());
413         }
414     }
415
416     @Override
417     protected void render(GLCanvas canvas) {
418         mUploadQuota = UPLOAD_LIMIT;
419         mRenderComplete = true;
420
421         int level = mLevel;
422         int rotation = mRotation;
423         int flags = 0;
424         if (rotation != 0) flags |= GLCanvas.SAVE_FLAG_MATRIX;
425
426         if (flags != 0) {
427             canvas.save(flags);
428             if (rotation != 0) {
429                 int centerX = getWidth() / 2, centerY = getHeight() / 2;
430                 canvas.translate(centerX, centerY);
431                 canvas.rotate(rotation, 0, 0, 1);
432                 canvas.translate(-centerX, -centerY);
433             }
434         }
435         try {
436             if (level != mLevelCount && !isScreenNailAnimating()) {
437                 if (mScreenNail != null) {
438                     mScreenNail.noDraw();
439                 }
440
441                 int size = (sTileSize << level);
442                 float length = size * mScale;
443                 Rect r = mTileRange;
444
445                 for (int ty = r.top, i = 0; ty < r.bottom; ty += size, i++) {
446                     float y = mOffsetY + i * length;
447                     for (int tx = r.left, j = 0; tx < r.right; tx += size, j++) {
448                         float x = mOffsetX + j * length;
449                         drawTile(canvas, tx, ty, level, x, y, length);
450                     }
451                 }
452             } else if (mScreenNail != null) {
453                 mScreenNail.draw(canvas, mOffsetX, mOffsetY,
454                         Math.round(mImageWidth * mScale),
455                         Math.round(mImageHeight * mScale));
456                 if (isScreenNailAnimating()) {
457                     invalidate();
458                 }
459             }
460         } finally {
461             if (flags != 0) canvas.restore();
462         }
463
464         if (mRenderComplete) {
465             if (!mBackgroundTileUploaded) uploadBackgroundTiles(canvas);
466         } else {
467             invalidate();
468         }
469     }
470
471     private boolean isScreenNailAnimating() {
472         return (mScreenNail instanceof TiledScreenNail)
473                 && ((TiledScreenNail) mScreenNail).isAnimating();
474     }
475
476     private void uploadBackgroundTiles(GLCanvas canvas) {
477         mBackgroundTileUploaded = true;
478         int n = mActiveTiles.size();
479         for (int i = 0; i < n; i++) {
480             Tile tile = mActiveTiles.valueAt(i);
481             if (!tile.isContentValid()) queueForDecode(tile);
482         }
483     }
484
485     void queueForUpload(Tile tile) {
486         synchronized (this) {
487             mUploadQueue.push(tile);
488         }
489         if (mTileUploader.mActive.compareAndSet(false, true)) {
490             getGLRoot().addOnGLIdleListener(mTileUploader);
491         }
492     }
493
494     synchronized void queueForDecode(Tile tile) {
495         if (tile.mTileState == STATE_ACTIVATED) {
496             tile.mTileState = STATE_IN_QUEUE;
497             if (mDecodeQueue.push(tile)) notifyAll();
498         }
499     }
500
501     boolean decodeTile(Tile tile) {
502         synchronized (this) {
503             if (tile.mTileState != STATE_IN_QUEUE) return false;
504             tile.mTileState = STATE_DECODING;
505         }
506         boolean decodeComplete = tile.decode();
507         synchronized (this) {
508             if (tile.mTileState == STATE_RECYCLING) {
509                 tile.mTileState = STATE_RECYCLED;
510                 if (tile.mDecodedTile != null) {
511                     if (sTilePool != null) sTilePool.recycle(tile.mDecodedTile);
512                     tile.mDecodedTile = null;
513                 }
514                 mRecycledQueue.push(tile);
515                 return false;
516             }
517             tile.mTileState = decodeComplete ? STATE_DECODED : STATE_DECODE_FAIL;
518             return decodeComplete;
519         }
520     }
521
522     private synchronized Tile obtainTile(int x, int y, int level) {
523         Tile tile = mRecycledQueue.pop();
524         if (tile != null) {
525             tile.mTileState = STATE_ACTIVATED;
526             tile.update(x, y, level);
527             return tile;
528         }
529         return new Tile(x, y, level);
530     }
531
532     synchronized void recycleTile(Tile tile) {
533         if (tile.mTileState == STATE_DECODING) {
534             tile.mTileState = STATE_RECYCLING;
535             return;
536         }
537         tile.mTileState = STATE_RECYCLED;
538         if (tile.mDecodedTile != null) {
539             if (sTilePool != null) sTilePool.recycle(tile.mDecodedTile);
540             tile.mDecodedTile = null;
541         }
542         mRecycledQueue.push(tile);
543     }
544
545     private void activateTile(int x, int y, int level) {
546         long key = makeTileKey(x, y, level);
547         Tile tile = mActiveTiles.get(key);
548         if (tile != null) {
549             if (tile.mTileState == STATE_IN_QUEUE) {
550                 tile.mTileState = STATE_ACTIVATED;
551             }
552             return;
553         }
554         tile = obtainTile(x, y, level);
555         mActiveTiles.put(key, tile);
556     }
557
558     private Tile getTile(int x, int y, int level) {
559         return mActiveTiles.get(makeTileKey(x, y, level));
560     }
561
562     private static long makeTileKey(int x, int y, int level) {
563         long result = x;
564         result = (result << 16) | y;
565         result = (result << 16) | level;
566         return result;
567     }
568
569     private class TileUploader implements GLRoot.OnGLIdleListener {
570         AtomicBoolean mActive = new AtomicBoolean(false);
571
572         @Override
573         public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
574             // Skips uploading if there is a pending rendering request.
575             // Returns true to keep uploading in next rendering loop.
576             if (renderRequested) return true;
577             int quota = UPLOAD_LIMIT;
578             Tile tile = null;
579             while (quota > 0) {
580                 synchronized (TileImageView.this) {
581                     tile = mUploadQueue.pop();
582                 }
583                 if (tile == null) break;
584                 if (!tile.isContentValid()) {
585                     boolean hasBeenLoaded = tile.isLoaded();
586                     Utils.assertTrue(tile.mTileState == STATE_DECODED);
587                     tile.updateContent(canvas);
588                     if (!hasBeenLoaded) tile.draw(canvas, 0, 0);
589                     --quota;
590                 }
591             }
592             if (tile == null) mActive.set(false);
593             return tile != null;
594         }
595     }
596
597     // Draw the tile to a square at canvas that locates at (x, y) and
598     // has a side length of length.
599     public void drawTile(GLCanvas canvas,
600             int tx, int ty, int level, float x, float y, float length) {
601         RectF source = mSourceRect;
602         RectF target = mTargetRect;
603         target.set(x, y, x + length, y + length);
604         source.set(0, 0, sTileSize, sTileSize);
605
606         Tile tile = getTile(tx, ty, level);
607         if (tile != null) {
608             if (!tile.isContentValid()) {
609                 if (tile.mTileState == STATE_DECODED) {
610                     if (mUploadQuota > 0) {
611                         --mUploadQuota;
612                         tile.updateContent(canvas);
613                     } else {
614                         mRenderComplete = false;
615                     }
616                 } else if (tile.mTileState != STATE_DECODE_FAIL){
617                     mRenderComplete = false;
618                     queueForDecode(tile);
619                 }
620             }
621             if (drawTile(tile, canvas, source, target)) return;
622         }
623         if (mScreenNail != null) {
624             int size = sTileSize << level;
625             float scaleX = (float) mScreenNail.getWidth() / mImageWidth;
626             float scaleY = (float) mScreenNail.getHeight() / mImageHeight;
627             source.set(tx * scaleX, ty * scaleY, (tx + size) * scaleX,
628                     (ty + size) * scaleY);
629             mScreenNail.draw(canvas, source, target);
630         }
631     }
632
633     static boolean drawTile(
634             Tile tile, GLCanvas canvas, RectF source, RectF target) {
635         while (true) {
636             if (tile.isContentValid()) {
637                 canvas.drawTexture(tile, source, target);
638                 return true;
639             }
640
641             // Parent can be divided to four quads and tile is one of the four.
642             Tile parent = tile.getParentTile();
643             if (parent == null) return false;
644             if (tile.mX == parent.mX) {
645                 source.left /= 2f;
646                 source.right /= 2f;
647             } else {
648                 source.left = (sTileSize + source.left) / 2f;
649                 source.right = (sTileSize + source.right) / 2f;
650             }
651             if (tile.mY == parent.mY) {
652                 source.top /= 2f;
653                 source.bottom /= 2f;
654             } else {
655                 source.top = (sTileSize + source.top) / 2f;
656                 source.bottom = (sTileSize + source.bottom) / 2f;
657             }
658             tile = parent;
659         }
660     }
661
662     private class Tile extends UploadedTexture {
663         public int mX;
664         public int mY;
665         public int mTileLevel;
666         public Tile mNext;
667         public Bitmap mDecodedTile;
668         public volatile int mTileState = STATE_ACTIVATED;
669
670         public Tile(int x, int y, int level) {
671             mX = x;
672             mY = y;
673             mTileLevel = level;
674         }
675
676         @Override
677         protected void onFreeBitmap(Bitmap bitmap) {
678             if (sTilePool != null) sTilePool.recycle(bitmap);
679         }
680
681         boolean decode() {
682             // Get a tile from the original image. The tile is down-scaled
683             // by (1 << mTilelevel) from a region in the original image.
684             try {
685                 mDecodedTile = DecodeUtils.ensureGLCompatibleBitmap(mModel.getTile(
686                         mTileLevel, mX, mY, sTileSize, sTilePool));
687             } catch (Throwable t) {
688                 Log.w(TAG, "fail to decode tile", t);
689             }
690             return mDecodedTile != null;
691         }
692
693         @Override
694         protected Bitmap onGetBitmap() {
695             Utils.assertTrue(mTileState == STATE_DECODED);
696
697             // We need to override the width and height, so that we won't
698             // draw beyond the boundaries.
699             int rightEdge = ((mImageWidth - mX) >> mTileLevel);
700             int bottomEdge = ((mImageHeight - mY) >> mTileLevel);
701             setSize(Math.min(sTileSize, rightEdge), Math.min(sTileSize, bottomEdge));
702
703             Bitmap bitmap = mDecodedTile;
704             mDecodedTile = null;
705             mTileState = STATE_ACTIVATED;
706             return bitmap;
707         }
708
709         // We override getTextureWidth() and getTextureHeight() here, so the
710         // texture can be re-used for different tiles regardless of the actual
711         // size of the tile (which may be small because it is a tile at the
712         // boundary).
713         @Override
714         public int getTextureWidth() {
715             return sTileSize;
716         }
717
718         @Override
719         public int getTextureHeight() {
720             return sTileSize;
721         }
722
723         public void update(int x, int y, int level) {
724             mX = x;
725             mY = y;
726             mTileLevel = level;
727             invalidateContent();
728         }
729
730         public Tile getParentTile() {
731             if (mTileLevel + 1 == mLevelCount) return null;
732             int size = sTileSize << (mTileLevel + 1);
733             int x = size * (mX / size);
734             int y = size * (mY / size);
735             return getTile(x, y, mTileLevel + 1);
736         }
737
738         @Override
739         public String toString() {
740             return String.format("tile(%s, %s, %s / %s)",
741                     mX / sTileSize, mY / sTileSize, mLevel, mLevelCount);
742         }
743     }
744
745     private static class TileQueue {
746         private Tile mHead;
747
748         public Tile pop() {
749             Tile tile = mHead;
750             if (tile != null) mHead = tile.mNext;
751             return tile;
752         }
753
754         public boolean push(Tile tile) {
755             boolean wasEmpty = mHead == null;
756             tile.mNext = mHead;
757             mHead = tile;
758             return wasEmpty;
759         }
760
761         public void clean() {
762             mHead = null;
763         }
764     }
765
766     private class TileDecoder implements ThreadPool.Job<Void> {
767
768         private CancelListener mNotifier = new CancelListener() {
769             @Override
770             public void onCancel() {
771                 synchronized (TileImageView.this) {
772                     TileImageView.this.notifyAll();
773                 }
774             }
775         };
776
777         @Override
778         public Void run(JobContext jc) {
779             jc.setMode(ThreadPool.MODE_NONE);
780             jc.setCancelListener(mNotifier);
781             while (!jc.isCancelled()) {
782                 Tile tile = null;
783                 synchronized(TileImageView.this) {
784                     tile = mDecodeQueue.pop();
785                     if (tile == null && !jc.isCancelled()) {
786                         Utils.waitWithoutInterrupt(TileImageView.this);
787                     }
788                 }
789                 if (tile == null) continue;
790                 if (decodeTile(tile)) queueForUpload(tile);
791             }
792             return null;
793         }
794     }
795 }