diff options
-rw-r--r-- | src/com/android/photos/BitmapRegionTileSource.java | 87 | ||||
-rw-r--r-- | src/com/android/photos/FullscreenViewer.java | 44 | ||||
-rw-r--r-- | src/com/android/photos/PhotoSetFragment.java | 21 | ||||
-rw-r--r-- | src/com/android/photos/views/BlockingGLTextureView.java | 427 | ||||
-rw-r--r-- | src/com/android/photos/views/TiledImageRenderer.java | 751 | ||||
-rw-r--r-- | src/com/android/photos/views/TiledImageView.java | 269 |
6 files changed, 1597 insertions, 2 deletions
diff --git a/src/com/android/photos/BitmapRegionTileSource.java b/src/com/android/photos/BitmapRegionTileSource.java new file mode 100644 index 000000000..1c7115191 --- /dev/null +++ b/src/com/android/photos/BitmapRegionTileSource.java @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.photos; + +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.BitmapRegionDecoder; +import android.graphics.Rect; +import android.util.Log; +import com.android.photos.views.TiledImageRenderer; + +import java.io.IOException; + +public class BitmapRegionTileSource implements TiledImageRenderer.TileSource { + + BitmapRegionDecoder mDecoder; + + + public BitmapRegionTileSource(String path) { + try { + mDecoder = BitmapRegionDecoder.newInstance(path, true); + } catch (IOException e) { + Log.w("BitmapRegionTileSource", "ctor failed", e); + } + } + + @Override + public int getTileSize() { + return 256; + } + + @Override + public int getImageWidth() { + return mDecoder.getWidth(); + } + + @Override + public int getImageHeight() { + return mDecoder.getHeight(); + } + + @Override + public Bitmap getTile(int level, int x, int y, Bitmap bitmap) { + int tileSize = getTileSize(); + int t = tileSize << level; + + Rect wantRegion = new Rect(x, y, x + t, y + t); + + if (bitmap == null) { + bitmap = Bitmap.createBitmap(tileSize, tileSize, Bitmap.Config.ARGB_8888); + } + + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inPreferredConfig = Bitmap.Config.ARGB_8888; + options.inPreferQualityOverSpeed = true; + options.inSampleSize = (1 << level); + options.inBitmap = bitmap; + + try { + // In CropImage, we may call the decodeRegion() concurrently. + bitmap = mDecoder.decodeRegion(wantRegion, options); + } finally { + if (options.inBitmap != bitmap && options.inBitmap != null) { + options.inBitmap = null; + } + } + + if (bitmap == null) { + Log.w("BitmapRegionTileSource", "fail in decoding region"); + } + return bitmap; + } +} diff --git a/src/com/android/photos/FullscreenViewer.java b/src/com/android/photos/FullscreenViewer.java new file mode 100644 index 000000000..50ea1ba71 --- /dev/null +++ b/src/com/android/photos/FullscreenViewer.java @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.photos; + +import android.app.Activity; +import android.os.Bundle; +import com.android.photos.views.TiledImageView; + + +public class FullscreenViewer extends Activity { + + private TiledImageView mTextureView; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + String path = getIntent().getData().toString(); + mTextureView = new TiledImageView(this); + mTextureView.setTileSource(new BitmapRegionTileSource(path)); + setContentView(mTextureView); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + mTextureView.destroy(); + } + +} diff --git a/src/com/android/photos/PhotoSetFragment.java b/src/com/android/photos/PhotoSetFragment.java index a3406bea4..6c0e2e7c5 100644 --- a/src/com/android/photos/PhotoSetFragment.java +++ b/src/com/android/photos/PhotoSetFragment.java @@ -19,16 +19,17 @@ package com.android.photos; import android.app.Fragment; import android.app.LoaderManager.LoaderCallbacks; import android.content.Context; +import android.content.Intent; import android.content.Loader; import android.database.Cursor; +import android.net.Uri; import android.os.Bundle; -import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; +import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; -import android.widget.ImageView.ScaleType; import com.android.gallery3d.R; import com.android.photos.data.PhotoSetLoader; @@ -81,7 +82,21 @@ public class PhotoSetFragment extends Fragment implements LoaderCallbacks<Cursor public void onLoaderReset(Loader<Cursor> loader) { } + private static class ShowFullScreen implements OnClickListener { + + @Override + public void onClick(View view) { + String path = (String) view.getTag(); + Intent intent = new Intent(view.getContext(), FullscreenViewer.class); + intent.setAction(Intent.ACTION_VIEW); + intent.setData(Uri.parse(path)); + view.getContext().startActivity(intent); + } + + } + private static class ThumbnailAdapter extends CursorAdapter implements GalleryThumbnailAdapter { + private static ShowFullScreen sShowFullscreenClickListener = new ShowFullScreen(); public ThumbnailAdapter(Context context) { super(context, null, false); @@ -95,6 +110,7 @@ public class PhotoSetFragment extends Fragment implements LoaderCallbacks<Cursor int height = cursor.getInt(PhotoSetLoader.INDEX_HEIGHT); String path = cursor.getString(PhotoSetLoader.INDEX_DATA); drawable.setImage(path, width, height); + iv.setTag(path); } @Override @@ -104,6 +120,7 @@ public class PhotoSetFragment extends Fragment implements LoaderCallbacks<Cursor iv.setImageDrawable(drawable); int padding = (int) Math.ceil(2 * context.getResources().getDisplayMetrics().density); iv.setPadding(padding, padding, padding, padding); + iv.setOnClickListener(sShowFullscreenClickListener); return iv; } diff --git a/src/com/android/photos/views/BlockingGLTextureView.java b/src/com/android/photos/views/BlockingGLTextureView.java new file mode 100644 index 000000000..c38f8f7a4 --- /dev/null +++ b/src/com/android/photos/views/BlockingGLTextureView.java @@ -0,0 +1,427 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.photos.views; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.graphics.SurfaceTexture; +import android.opengl.GLSurfaceView.Renderer; +import android.opengl.GLUtils; +import android.util.Log; +import android.view.TextureView; +import android.view.TextureView.SurfaceTextureListener; + +import javax.microedition.khronos.egl.EGL10; +import javax.microedition.khronos.egl.EGLConfig; +import javax.microedition.khronos.egl.EGLContext; +import javax.microedition.khronos.egl.EGLDisplay; +import javax.microedition.khronos.egl.EGLSurface; +import javax.microedition.khronos.opengles.GL10; + + +public class BlockingGLTextureView extends TextureView + implements SurfaceTextureListener { + + private RenderThread mRenderThread; + + public BlockingGLTextureView(Context context) { + super(context); + setSurfaceTextureListener(this); + } + + public void setRenderer(Renderer renderer) { + if (mRenderThread != null) { + throw new IllegalArgumentException("Renderer already set"); + } + mRenderThread = new RenderThread(renderer); + } + + public void render() { + mRenderThread.render(); + } + + public void destroy() { + if (mRenderThread != null) { + mRenderThread.finish(); + mRenderThread = null; + } + } + + @Override + public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, + int height) { + mRenderThread.setSurface(surface); + mRenderThread.setSize(width, height); + } + + @Override + public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, + int height) { + mRenderThread.setSize(width, height); + } + + @Override + public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { + if (mRenderThread != null) { + mRenderThread.setSurface(null); + } + return false; + } + + @Override + public void onSurfaceTextureUpdated(SurfaceTexture surface) { + } + + @Override + protected void finalize() throws Throwable { + try { + destroy(); + } catch (Throwable t) {} + super.finalize(); + } + + /** + * An EGL helper class. + */ + + private static class EglHelper { + private static final int EGL_CONTEXT_CLIENT_VERSION = 0x3098; + private static final int EGL_OPENGL_ES2_BIT = 4; + + EGL10 mEgl; + EGLDisplay mEglDisplay; + EGLSurface mEglSurface; + EGLConfig mEglConfig; + EGLContext mEglContext; + + private EGLConfig chooseEglConfig() { + int[] configsCount = new int[1]; + EGLConfig[] configs = new EGLConfig[1]; + int[] configSpec = getConfig(); + if (!mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, configsCount)) { + throw new IllegalArgumentException("eglChooseConfig failed " + + GLUtils.getEGLErrorString(mEgl.eglGetError())); + } else if (configsCount[0] > 0) { + return configs[0]; + } + return null; + } + + private static int[] getConfig() { + return new int[] { + EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, + EGL10.EGL_RED_SIZE, 8, + EGL10.EGL_GREEN_SIZE, 8, + EGL10.EGL_BLUE_SIZE, 8, + EGL10.EGL_ALPHA_SIZE, 8, + EGL10.EGL_DEPTH_SIZE, 0, + EGL10.EGL_STENCIL_SIZE, 0, + EGL10.EGL_NONE + }; + } + + EGLContext createContext(EGL10 egl, EGLDisplay eglDisplay, EGLConfig eglConfig) { + int[] attrib_list = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE }; + return egl.eglCreateContext(eglDisplay, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list); + } + + /** + * Initialize EGL for a given configuration spec. + */ + public void start() { + /* + * Get an EGL instance + */ + mEgl = (EGL10) EGLContext.getEGL(); + + /* + * Get to the default display. + */ + mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); + + if (mEglDisplay == EGL10.EGL_NO_DISPLAY) { + throw new RuntimeException("eglGetDisplay failed"); + } + + /* + * We can now initialize EGL for that display + */ + int[] version = new int[2]; + if(!mEgl.eglInitialize(mEglDisplay, version)) { + throw new RuntimeException("eglInitialize failed"); + } + mEglConfig = chooseEglConfig(); + + /* + * Create an EGL context. We want to do this as rarely as we can, because an + * EGL context is a somewhat heavy object. + */ + mEglContext = createContext(mEgl, mEglDisplay, mEglConfig); + + if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) { + mEglContext = null; + throwEglException("createContext"); + } + + mEglSurface = null; + } + + /** + * Create an egl surface for the current SurfaceTexture surface. If a surface + * already exists, destroy it before creating the new surface. + * + * @return true if the surface was created successfully. + */ + public boolean createSurface(SurfaceTexture surface) { + /* + * Check preconditions. + */ + if (mEgl == null) { + throw new RuntimeException("egl not initialized"); + } + if (mEglDisplay == null) { + throw new RuntimeException("eglDisplay not initialized"); + } + if (mEglConfig == null) { + throw new RuntimeException("mEglConfig not initialized"); + } + + /* + * The window size has changed, so we need to create a new + * surface. + */ + destroySurfaceImp(); + + /* + * Create an EGL surface we can render into. + */ + if (surface != null) { + mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, surface, null); + } else { + mEglSurface = null; + } + + if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) { + int error = mEgl.eglGetError(); + if (error == EGL10.EGL_BAD_NATIVE_WINDOW) { + Log.e("EglHelper", "createWindowSurface returned EGL_BAD_NATIVE_WINDOW."); + } + return false; + } + + /* + * Before we can issue GL commands, we need to make sure + * the context is current and bound to a surface. + */ + if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext)) { + /* + * Could not make the context current, probably because the underlying + * SurfaceView surface has been destroyed. + */ + logEglErrorAsWarning("EGLHelper", "eglMakeCurrent", mEgl.eglGetError()); + return false; + } + + return true; + } + + /** + * Create a GL object for the current EGL context. + */ + public GL10 createGL() { + return (GL10) mEglContext.getGL(); + } + + /** + * Display the current render surface. + * @return the EGL error code from eglSwapBuffers. + */ + public int swap() { + if (! mEgl.eglSwapBuffers(mEglDisplay, mEglSurface)) { + return mEgl.eglGetError(); + } + return EGL10.EGL_SUCCESS; + } + + public void destroySurface() { + destroySurfaceImp(); + } + + private void destroySurfaceImp() { + if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) { + mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, + EGL10.EGL_NO_SURFACE, + EGL10.EGL_NO_CONTEXT); + mEgl.eglDestroySurface(mEglDisplay, mEglSurface); + mEglSurface = null; + } + } + + public void finish() { + if (mEglContext != null) { + mEgl.eglDestroyContext(mEglDisplay, mEglContext); + mEglContext = null; + } + if (mEglDisplay != null) { + mEgl.eglTerminate(mEglDisplay); + mEglDisplay = null; + } + } + + private void throwEglException(String function) { + throwEglException(function, mEgl.eglGetError()); + } + + public static void throwEglException(String function, int error) { + String message = formatEglError(function, error); + throw new RuntimeException(message); + } + + public static void logEglErrorAsWarning(String tag, String function, int error) { + Log.w(tag, formatEglError(function, error)); + } + + public static String formatEglError(String function, int error) { + return function + " failed: " + error; + } + + } + + private static class RenderThread extends Thread { + private static final int INVALID = -1; + private static final int RENDER = 1; + private static final int CHANGE_SURFACE = 2; + private static final int RESIZE_SURFACE = 3; + private static final int FINISH = 4; + + private EglHelper mEglHelper = new EglHelper(); + + private Object mLock = new Object(); + private int mExecMsgId = INVALID; + private SurfaceTexture mSurface; + private Renderer mRenderer; + private int mWidth, mHeight; + + private boolean mFinished = false; + private GL10 mGL; + + public RenderThread(Renderer renderer) { + super("RenderThread"); + mRenderer = renderer; + start(); + } + + private void checkRenderer() { + if (mRenderer == null) { + throw new IllegalArgumentException("Renderer is null!"); + } + } + + private void checkSurface() { + if (mSurface == null) { + throw new IllegalArgumentException("surface is null!"); + } + } + + public void setSurface(SurfaceTexture surface) { + // If the surface is null we're being torn down, don't need a + // renderer then + if (surface != null) { + checkRenderer(); + } + mSurface = surface; + exec(CHANGE_SURFACE); + } + + public void setSize(int width, int height) { + checkRenderer(); + checkSurface(); + mWidth = width; + mHeight = height; + exec(RESIZE_SURFACE); + } + + public void render() { + checkRenderer(); + if (mSurface != null) { + exec(RENDER); + mSurface.updateTexImage(); + } + } + + public void finish() { + mSurface = null; + exec(FINISH); + try { + join(); + } catch (InterruptedException e) {} + } + + private void exec(int msgid) { + synchronized (mLock) { + if (mExecMsgId != INVALID) { + throw new IllegalArgumentException("Message already set - multithreaded access?"); + } + mExecMsgId = msgid; + mLock.notify(); + try { + mLock.wait(); + } catch (InterruptedException e) {} + } + } + + private void handleMessageLocked(int what) { + switch (what) { + case CHANGE_SURFACE: + if (mEglHelper.createSurface(mSurface)) { + mGL = mEglHelper.createGL(); + mRenderer.onSurfaceCreated(mGL, mEglHelper.mEglConfig); + } + break; + case RESIZE_SURFACE: + mRenderer.onSurfaceChanged(mGL, mWidth, mHeight); + break; + case RENDER: + mRenderer.onDrawFrame(mGL); + mEglHelper.swap(); + break; + case FINISH: + mEglHelper.destroySurface(); + mEglHelper.finish(); + mFinished = true; + break; + } + } + + @Override + public void run() { + synchronized (mLock) { + mEglHelper.start(); + while (!mFinished) { + while (mExecMsgId == INVALID) { + try { + mLock.wait(); + } catch (InterruptedException e) {} + } + handleMessageLocked(mExecMsgId); + mExecMsgId = INVALID; + mLock.notify(); + } + } + } + } +} diff --git a/src/com/android/photos/views/TiledImageRenderer.java b/src/com/android/photos/views/TiledImageRenderer.java new file mode 100644 index 000000000..a1f7107f2 --- /dev/null +++ b/src/com/android/photos/views/TiledImageRenderer.java @@ -0,0 +1,751 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.photos.views; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Rect; +import android.graphics.RectF; +import android.support.v4.util.LongSparseArray; +import android.util.DisplayMetrics; +import android.util.Log; +import android.view.View; +import android.view.WindowManager; + +import com.android.gallery3d.common.Utils; +import com.android.gallery3d.glrenderer.GLCanvas; +import com.android.gallery3d.glrenderer.UploadedTexture; +import com.android.photos.data.GalleryBitmapPool; + +public class TiledImageRenderer { + public static final int SIZE_UNKNOWN = -1; + + private static final String TAG = "TiledImageRenderer"; + private static final int UPLOAD_LIMIT = 1; + + /* + * This is the tile state in the CPU side. + * Life of a Tile: + * ACTIVATED (initial state) + * --> IN_QUEUE - by queueForDecode() + * --> RECYCLED - by recycleTile() + * IN_QUEUE --> DECODING - by decodeTile() + * --> RECYCLED - by recycleTile) + * DECODING --> RECYCLING - by recycleTile() + * --> DECODED - by decodeTile() + * --> DECODE_FAIL - by decodeTile() + * RECYCLING --> RECYCLED - by decodeTile() + * DECODED --> ACTIVATED - (after the decoded bitmap is uploaded) + * DECODED --> RECYCLED - by recycleTile() + * DECODE_FAIL -> RECYCLED - by recycleTile() + * RECYCLED --> ACTIVATED - by obtainTile() + */ + private static final int STATE_ACTIVATED = 0x01; + private static final int STATE_IN_QUEUE = 0x02; + private static final int STATE_DECODING = 0x04; + private static final int STATE_DECODED = 0x08; + private static final int STATE_DECODE_FAIL = 0x10; + private static final int STATE_RECYCLING = 0x20; + private static final int STATE_RECYCLED = 0x40; + + private static GalleryBitmapPool sTilePool = GalleryBitmapPool.getInstance(); + + // TILE_SIZE must be 2^N + private int mTileSize; + + private TileSource mModel; + protected int mLevelCount; // cache the value of mScaledBitmaps.length + + // The mLevel variable indicates which level of bitmap we should use. + // Level 0 means the original full-sized bitmap, and a larger value means + // a smaller scaled bitmap (The width and height of each scaled bitmap is + // half size of the previous one). If the value is in [0, mLevelCount), we + // use the bitmap in mScaledBitmaps[mLevel] for display, otherwise the value + // is mLevelCount + private int mLevel = 0; + + private int mOffsetX; + private int mOffsetY; + + private int mUploadQuota; + private boolean mRenderComplete; + + private final RectF mSourceRect = new RectF(); + private final RectF mTargetRect = new RectF(); + + private final LongSparseArray<Tile> mActiveTiles = new LongSparseArray<Tile>(); + + // The following three queue are guarded by mQueueLock + private final Object mQueueLock = new Object(); + private final TileQueue mRecycledQueue = new TileQueue(); + private final TileQueue mUploadQueue = new TileQueue(); + private final TileQueue mDecodeQueue = new TileQueue(); + + // The width and height of the full-sized bitmap + protected int mImageWidth = SIZE_UNKNOWN; + protected int mImageHeight = SIZE_UNKNOWN; + + protected int mCenterX; + protected int mCenterY; + protected float mScale; + protected int mRotation; + + private boolean mLayoutTiles; + + // Temp variables to avoid memory allocation + private final Rect mTileRange = new Rect(); + private final Rect mActiveRange[] = {new Rect(), new Rect()}; + + private TileDecoder mTileDecoder; + private boolean mBackgroundTileUploaded; + + private int mViewWidth, mViewHeight; + private View mParent; + + public static interface TileSource { + public int getTileSize(); + public int getImageWidth(); + public int getImageHeight(); + + // The tile returned by this method can be specified this way: Assuming + // the image size is (width, height), first take the intersection of (0, + // 0) - (width, height) and (x, y) - (x + tileSize, y + tileSize). If + // in extending the region, we found some part of the region is outside + // the image, those pixels are filled with black. + // + // If level > 0, it does the same operation on a down-scaled version of + // the original image (down-scaled by a factor of 2^level), but (x, y) + // still refers to the coordinate on the original image. + // + // The method would be called by the decoder thread. + public Bitmap getTile(int level, int x, int y, Bitmap reuse); + } + + public static int suggestedTileSize(Context context) { + return isHighResolution(context) ? 512 : 256; + } + + private static boolean isHighResolution(Context context) { + DisplayMetrics metrics = new DisplayMetrics(); + WindowManager wm = (WindowManager) + context.getSystemService(Context.WINDOW_SERVICE); + wm.getDefaultDisplay().getMetrics(metrics); + return metrics.heightPixels > 2048 || metrics.widthPixels > 2048; + } + + public TiledImageRenderer(View parent) { + mParent = parent; + mTileDecoder = new TileDecoder(); + mTileDecoder.start(); + } + + public int getViewWidth() { + return mViewWidth; + } + + public int getViewHeight() { + return mViewHeight; + } + + private void invalidate() { + mParent.postInvalidate(); + } + + public void setModel(TileSource model, int rotation) { + if (mModel != model) { + mModel = model; + notifyModelInvalidated(); + } + if (mRotation != rotation) { + mRotation = rotation; + mLayoutTiles = true; + invalidate(); + } + } + + private static int calulateLevelCount(TileSource source) { + int levels = 1; + int maxDim = Math.max(source.getImageWidth(), source.getImageHeight()); + int t = source.getTileSize(); + while (t < maxDim) { + t <<= 1; + levels++; + } + return levels; + } + + public void notifyModelInvalidated() { + invalidateTiles(); + if (mModel == null) { + mImageWidth = 0; + mImageHeight = 0; + mLevelCount = 0; + } else { + mImageWidth = mModel.getImageWidth(); + mImageHeight = mModel.getImageHeight(); + mLevelCount = calulateLevelCount(mModel); + mTileSize = mModel.getTileSize(); + } + mLayoutTiles = true; + invalidate(); + } + + public void setViewSize(int width, int height) { + mViewWidth = width; + mViewHeight = height; + } + + public void setPosition(int centerX, int centerY, float scale) { + if (mCenterX == centerX && mCenterY == centerY + && mScale == scale) return; + mCenterX = centerX; + mCenterY = centerY; + mScale = scale; + mLayoutTiles = true; + invalidate(); + } + + // Prepare the tiles we want to use for display. + // + // 1. Decide the tile level we want to use for display. + // 2. Decide the tile levels we want to keep as texture (in addition to + // the one we use for display). + // 3. Recycle unused tiles. + // 4. Activate the tiles we want. + private void layoutTiles() { + if (mViewWidth == 0 || mViewHeight == 0 || !mLayoutTiles) { + return; + } + mLayoutTiles = false; + + // The tile levels we want to keep as texture is in the range + // [fromLevel, endLevel). + int fromLevel; + int endLevel; + + // We want to use a texture larger than or equal to the display size. + mLevel = Utils.clamp(Utils.floorLog2(1f / mScale), 0, mLevelCount); + + // We want to keep one more tile level as texture in addition to what + // we use for display. So it can be faster when the scale moves to the + // next level. We choose the level closest to the current scale. + if (mLevel != mLevelCount) { + Rect range = mTileRange; + getRange(range, mCenterX, mCenterY, mLevel, mScale, mRotation); + mOffsetX = Math.round(mViewWidth / 2f + (range.left - mCenterX) * mScale); + mOffsetY = Math.round(mViewHeight / 2f + (range.top - mCenterY) * mScale); + fromLevel = mScale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel; + } else { + // Activate the tiles of the smallest two levels. + fromLevel = mLevel - 2; + mOffsetX = Math.round(mViewWidth / 2f - mCenterX * mScale); + mOffsetY = Math.round(mViewHeight / 2f - mCenterY * mScale); + } + + fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2)); + endLevel = Math.min(fromLevel + 2, mLevelCount); + + Rect range[] = mActiveRange; + for (int i = fromLevel; i < endLevel; ++i) { + getRange(range[i - fromLevel], mCenterX, mCenterY, i, mRotation); + } + + // If rotation is transient, don't update the tile. + if (mRotation % 90 != 0) return; + + synchronized (mQueueLock) { + mDecodeQueue.clean(); + mUploadQueue.clean(); + mBackgroundTileUploaded = false; + + // Recycle unused tiles: if the level of the active tile is outside the + // range [fromLevel, endLevel) or not in the visible range. + int n = mActiveTiles.size(); + for (int i = 0; i < n; i++) { + Tile tile = mActiveTiles.valueAt(i); + int level = tile.mTileLevel; + if (level < fromLevel || level >= endLevel + || !range[level - fromLevel].contains(tile.mX, tile.mY)) { + mActiveTiles.removeAt(i); + i--; + n--; + recycleTile(tile); + } + } + } + + for (int i = fromLevel; i < endLevel; ++i) { + int size = mTileSize << i; + Rect r = range[i - fromLevel]; + for (int y = r.top, bottom = r.bottom; y < bottom; y += size) { + for (int x = r.left, right = r.right; x < right; x += size) { + activateTile(x, y, i); + } + } + } + invalidate(); + } + + private void invalidateTiles() { + synchronized (mQueueLock) { + mDecodeQueue.clean(); + mUploadQueue.clean(); + + // TODO disable decoder + int n = mActiveTiles.size(); + for (int i = 0; i < n; i++) { + Tile tile = mActiveTiles.valueAt(i); + recycleTile(tile); + } + mActiveTiles.clear(); + } + } + + private void getRange(Rect out, int cX, int cY, int level, int rotation) { + getRange(out, cX, cY, level, 1f / (1 << (level + 1)), rotation); + } + + // If the bitmap is scaled by the given factor "scale", return the + // rectangle containing visible range. The left-top coordinate returned is + // aligned to the tile boundary. + // + // (cX, cY) is the point on the original bitmap which will be put in the + // center of the ImageViewer. + private void getRange(Rect out, + int cX, int cY, int level, float scale, int rotation) { + + double radians = Math.toRadians(-rotation); + double w = mViewWidth; + double h = mViewHeight; + + double cos = Math.cos(radians); + double sin = Math.sin(radians); + int width = (int) Math.ceil(Math.max( + Math.abs(cos * w - sin * h), Math.abs(cos * w + sin * h))); + int height = (int) Math.ceil(Math.max( + Math.abs(sin * w + cos * h), Math.abs(sin * w - cos * h))); + + int left = (int) Math.floor(cX - width / (2f * scale)); + int top = (int) Math.floor(cY - height / (2f * scale)); + int right = (int) Math.ceil(left + width / scale); + int bottom = (int) Math.ceil(top + height / scale); + + // align the rectangle to tile boundary + int size = mTileSize << level; + left = Math.max(0, size * (left / size)); + top = Math.max(0, size * (top / size)); + right = Math.min(mImageWidth, right); + bottom = Math.min(mImageHeight, bottom); + + out.set(left, top, right, bottom); + } + + public void freeTextures() { + mLayoutTiles = true; + + synchronized (mQueueLock) { + mUploadQueue.clean(); + mDecodeQueue.clean(); + Tile tile = mRecycledQueue.pop(); + while (tile != null) { + tile.recycle(); + tile = mRecycledQueue.pop(); + } + } + + int n = mActiveTiles.size(); + for (int i = 0; i < n; i++) { + Tile texture = mActiveTiles.valueAt(i); + texture.recycle(); + } + mActiveTiles.clear(); + mTileRange.set(0, 0, 0, 0); + + if (sTilePool != null) sTilePool.clear(); + } + + public void draw(GLCanvas canvas) { + layoutTiles(); + uploadTiles(canvas); + + mUploadQuota = UPLOAD_LIMIT; + mRenderComplete = true; + + int level = mLevel; + int rotation = mRotation; + int flags = 0; + if (rotation != 0) flags |= GLCanvas.SAVE_FLAG_MATRIX; + + if (flags != 0) { + canvas.save(flags); + if (rotation != 0) { + int centerX = mViewWidth / 2, centerY = mViewHeight / 2; + canvas.translate(centerX, centerY); + canvas.rotate(rotation, 0, 0, 1); + canvas.translate(-centerX, -centerY); + } + } + try { + if (level != mLevelCount) { + int size = (mTileSize << level); + float length = size * mScale; + Rect r = mTileRange; + + for (int ty = r.top, i = 0; ty < r.bottom; ty += size, i++) { + float y = mOffsetY + i * length; + for (int tx = r.left, j = 0; tx < r.right; tx += size, j++) { + float x = mOffsetX + j * length; + drawTile(canvas, tx, ty, level, x, y, length); + } + } + } + } finally { + if (flags != 0) canvas.restore(); + } + + if (mRenderComplete) { + if (!mBackgroundTileUploaded) { + uploadBackgroundTiles(canvas); + } + } else { + invalidate(); + } + } + + private void uploadBackgroundTiles(GLCanvas canvas) { + mBackgroundTileUploaded = true; + int n = mActiveTiles.size(); + for (int i = 0; i < n; i++) { + Tile tile = mActiveTiles.valueAt(i); + if (!tile.isContentValid()) { + queueForDecode(tile); + } + } + } + + private void queueForUpload(Tile tile) { + synchronized (mQueueLock) { + mUploadQueue.push(tile); + } + invalidate(); + // TODO +// if (mTileUploader.mActive.compareAndSet(false, true)) { +// getGLRoot().addOnGLIdleListener(mTileUploader); +// } + } + + private void queueForDecode(Tile tile) { + synchronized (mQueueLock) { + if (tile.mTileState == STATE_ACTIVATED) { + tile.mTileState = STATE_IN_QUEUE; + if (mDecodeQueue.push(tile)) { + mQueueLock.notifyAll(); + } + } + } + } + + private boolean decodeTile(Tile tile) { + synchronized (mQueueLock) { + if (tile.mTileState != STATE_IN_QUEUE) return false; + tile.mTileState = STATE_DECODING; + } + boolean decodeComplete = tile.decode(); + synchronized (mQueueLock) { + if (tile.mTileState == STATE_RECYCLING) { + tile.mTileState = STATE_RECYCLED; + if (tile.mDecodedTile != null) { + if (sTilePool != null) sTilePool.put(tile.mDecodedTile); + tile.mDecodedTile = null; + } + mRecycledQueue.push(tile); + return false; + } + tile.mTileState = decodeComplete ? STATE_DECODED : STATE_DECODE_FAIL; + return decodeComplete; + } + } + + private Tile obtainTile(int x, int y, int level) { + synchronized (mQueueLock) { + Tile tile = mRecycledQueue.pop(); + if (tile != null) { + tile.mTileState = STATE_ACTIVATED; + tile.update(x, y, level); + return tile; + } + return new Tile(x, y, level); + } + } + + private void recycleTile(Tile tile) { + synchronized (mQueueLock) { + if (tile.mTileState == STATE_DECODING) { + tile.mTileState = STATE_RECYCLING; + return; + } + tile.mTileState = STATE_RECYCLED; + if (tile.mDecodedTile != null) { + if (sTilePool != null) sTilePool.put(tile.mDecodedTile); + tile.mDecodedTile = null; + } + mRecycledQueue.push(tile); + } + } + + private void activateTile(int x, int y, int level) { + long key = makeTileKey(x, y, level); + Tile tile = mActiveTiles.get(key); + if (tile != null) { + if (tile.mTileState == STATE_IN_QUEUE) { + tile.mTileState = STATE_ACTIVATED; + } + return; + } + tile = obtainTile(x, y, level); + mActiveTiles.put(key, tile); + } + + private Tile getTile(int x, int y, int level) { + return mActiveTiles.get(makeTileKey(x, y, level)); + } + + private static long makeTileKey(int x, int y, int level) { + long result = x; + result = (result << 16) | y; + result = (result << 16) | level; + return result; + } + + private void uploadTiles(GLCanvas canvas) { + int quota = UPLOAD_LIMIT; + Tile tile = null; + while (quota > 0) { + synchronized (mQueueLock) { + tile = mUploadQueue.pop(); + } + if (tile == null) break; + if (!tile.isContentValid()) { + Utils.assertTrue(tile.mTileState == STATE_DECODED); + tile.updateContent(canvas); + --quota; + } + } + if (tile != null) { + invalidate(); + } + } + + // Draw the tile to a square at canvas that locates at (x, y) and + // has a side length of length. + private void drawTile(GLCanvas canvas, + int tx, int ty, int level, float x, float y, float length) { + RectF source = mSourceRect; + RectF target = mTargetRect; + target.set(x, y, x + length, y + length); + source.set(0, 0, mTileSize, mTileSize); + + Tile tile = getTile(tx, ty, level); + if (tile != null) { + if (!tile.isContentValid()) { + if (tile.mTileState == STATE_DECODED) { + if (mUploadQuota > 0) { + --mUploadQuota; + tile.updateContent(canvas); + } else { + mRenderComplete = false; + } + } else if (tile.mTileState != STATE_DECODE_FAIL){ + mRenderComplete = false; + queueForDecode(tile); + } + } + drawTile(tile, canvas, source, target); + } + } + + private boolean drawTile( + Tile tile, GLCanvas canvas, RectF source, RectF target) { + while (true) { + if (tile.isContentValid()) { + canvas.drawTexture(tile, source, target); + return true; + } + + // Parent can be divided to four quads and tile is one of the four. + Tile parent = tile.getParentTile(); + if (parent == null) return false; + if (tile.mX == parent.mX) { + source.left /= 2f; + source.right /= 2f; + } else { + source.left = (mTileSize + source.left) / 2f; + source.right = (mTileSize + source.right) / 2f; + } + if (tile.mY == parent.mY) { + source.top /= 2f; + source.bottom /= 2f; + } else { + source.top = (mTileSize + source.top) / 2f; + source.bottom = (mTileSize + source.bottom) / 2f; + } + tile = parent; + } + } + + private class Tile extends UploadedTexture { + public int mX; + public int mY; + public int mTileLevel; + public Tile mNext; + public Bitmap mDecodedTile; + public volatile int mTileState = STATE_ACTIVATED; + + public Tile(int x, int y, int level) { + mX = x; + mY = y; + mTileLevel = level; + } + + @Override + protected void onFreeBitmap(Bitmap bitmap) { + if (sTilePool != null) sTilePool.put(bitmap); + } + + boolean decode() { + // Get a tile from the original image. The tile is down-scaled + // by (1 << mTilelevel) from a region in the original image. + try { + Bitmap reuse = sTilePool.get(mTileSize, mTileSize); + mDecodedTile = mModel.getTile(mTileLevel, mX, mY, reuse); + } catch (Throwable t) { + Log.w(TAG, "fail to decode tile", t); + } + return mDecodedTile != null; + } + + @Override + protected Bitmap onGetBitmap() { + Utils.assertTrue(mTileState == STATE_DECODED); + + // We need to override the width and height, so that we won't + // draw beyond the boundaries. + int rightEdge = ((mImageWidth - mX) >> mTileLevel); + int bottomEdge = ((mImageHeight - mY) >> mTileLevel); + setSize(Math.min(mTileSize, rightEdge), Math.min(mTileSize, bottomEdge)); + + Bitmap bitmap = mDecodedTile; + mDecodedTile = null; + mTileState = STATE_ACTIVATED; + return bitmap; + } + + // We override getTextureWidth() and getTextureHeight() here, so the + // texture can be re-used for different tiles regardless of the actual + // size of the tile (which may be small because it is a tile at the + // boundary). + @Override + public int getTextureWidth() { + return mTileSize; + } + + @Override + public int getTextureHeight() { + return mTileSize; + } + + public void update(int x, int y, int level) { + mX = x; + mY = y; + mTileLevel = level; + invalidateContent(); + } + + public Tile getParentTile() { + if (mTileLevel + 1 == mLevelCount) return null; + int size = mTileSize << (mTileLevel + 1); + int x = size * (mX / size); + int y = size * (mY / size); + return getTile(x, y, mTileLevel + 1); + } + + @Override + public String toString() { + return String.format("tile(%s, %s, %s / %s)", + mX / mTileSize, mY / mTileSize, mLevel, mLevelCount); + } + } + + private static class TileQueue { + private Tile mHead; + + public Tile pop() { + Tile tile = mHead; + if (tile != null) mHead = tile.mNext; + return tile; + } + + public boolean push(Tile tile) { + boolean wasEmpty = mHead == null; + tile.mNext = mHead; + mHead = tile; + return wasEmpty; + } + + public void clean() { + mHead = null; + } + } + + private class TileDecoder extends Thread { + + public void finishAndWait() { + interrupt(); + try { + join(); + } catch (InterruptedException e) { + Log.w(TAG, "Interrupted while waiting for TileDecoder thread to finish!"); + } + } + + private Tile waitForTile() throws InterruptedException { + synchronized(mQueueLock) { + while (true) { + Tile tile = mDecodeQueue.pop(); + if (tile != null) { + return tile; + } + mQueueLock.wait(); + } + } + } + + @Override + public void run() { + try { + while (!isInterrupted()) { + Tile tile = waitForTile(); + if (decodeTile(tile)) { + queueForUpload(tile); + } + } + } catch (InterruptedException ex) { + } + } + + } +} diff --git a/src/com/android/photos/views/TiledImageView.java b/src/com/android/photos/views/TiledImageView.java new file mode 100644 index 000000000..6fe030dae --- /dev/null +++ b/src/com/android/photos/views/TiledImageView.java @@ -0,0 +1,269 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.photos.views; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Paint.Align; +import android.opengl.GLSurfaceView.Renderer; +import android.util.AttributeSet; +import android.view.MotionEvent; +import android.view.ScaleGestureDetector; +import android.view.ScaleGestureDetector.OnScaleGestureListener; +import android.widget.FrameLayout; +import com.android.gallery3d.glrenderer.GLES20Canvas; +import com.android.photos.views.TiledImageRenderer.TileSource; + +import javax.microedition.khronos.egl.EGLConfig; +import javax.microedition.khronos.opengles.GL10; + + +public class TiledImageView extends FrameLayout implements OnScaleGestureListener { + + private BlockingGLTextureView mTextureView; + private float mLastX, mLastY; + + private static class ImageRendererWrapper { + // Guarded by locks + float scale; + int centerX, centerY; + int rotation; + TileSource source; + + // GL thread only + TiledImageRenderer image; + } + + // TODO: left/right paging + private ImageRendererWrapper mRenderers[] = new ImageRendererWrapper[1]; + private ImageRendererWrapper mFocusedRenderer; + + // ------------------------- + // Guarded by mLock + // ------------------------- + private Object mLock = new Object(); + private ScaleGestureDetector mScaleGestureDetector; + + public TiledImageView(Context context) { + this(context, null); + } + + public TiledImageView(Context context, AttributeSet attrs) { + super(context, attrs); + mTextureView = new BlockingGLTextureView(context); + addView(mTextureView, new LayoutParams( + LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); + mTextureView.setRenderer(new TileRenderer()); + setTileSource(new ColoredTiles()); + mScaleGestureDetector = new ScaleGestureDetector(context, this); + } + + public void destroy() { + mTextureView.destroy(); + } + + public void setTileSource(TileSource source) { + synchronized (mLock) { + for (int i = 0; i < mRenderers.length; i++) { + ImageRendererWrapper renderer = mRenderers[i]; + if (renderer == null) { + renderer = mRenderers[i] = new ImageRendererWrapper(); + } + renderer.source = source; + renderer.centerX = renderer.source.getImageWidth() / 2; + renderer.centerY = renderer.source.getImageHeight() / 2; + renderer.rotation = 0; + renderer.scale = 0; + renderer.image = new TiledImageRenderer(this); + updateScaleIfNecessaryLocked(renderer); + } + } + mFocusedRenderer = mRenderers[0]; + invalidate(); + } + + @Override + public boolean onScaleBegin(ScaleGestureDetector detector) { + return true; + } + + @Override + public boolean onScale(ScaleGestureDetector detector) { + // Don't need the lock because this will only fire inside of onTouchEvent + mFocusedRenderer.scale *= detector.getScaleFactor(); + invalidate(); + return true; + } + + @Override + public void onScaleEnd(ScaleGestureDetector detector) { + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + int action = event.getActionMasked(); + final boolean pointerUp = action == MotionEvent.ACTION_POINTER_UP; + final int skipIndex = pointerUp ? event.getActionIndex() : -1; + + // Determine focal point + float sumX = 0, sumY = 0; + final int count = event.getPointerCount(); + for (int i = 0; i < count; i++) { + if (skipIndex == i) continue; + sumX += event.getX(i); + sumY += event.getY(i); + } + final int div = pointerUp ? count - 1 : count; + float x = sumX / div; + float y = sumY / div; + + synchronized (mLock) { + mScaleGestureDetector.onTouchEvent(event); + switch (action) { + case MotionEvent.ACTION_MOVE: + mFocusedRenderer.centerX += (mLastX - x) / mFocusedRenderer.scale; + mFocusedRenderer.centerY += (mLastY - y) / mFocusedRenderer.scale; + invalidate(); + break; + } + } + + mLastX = x; + mLastY = y; + return true; + } + + @Override + protected void onLayout(boolean changed, int left, int top, int right, + int bottom) { + super.onLayout(changed, left, top, right, bottom); + synchronized (mLock) { + for (ImageRendererWrapper renderer : mRenderers) { + updateScaleIfNecessaryLocked(renderer); + } + } + } + + private void updateScaleIfNecessaryLocked(ImageRendererWrapper renderer) { + if (renderer.scale > 0 || getWidth() == 0) return; + renderer.scale = Math.min( + (float) getWidth() / (float) renderer.source.getImageWidth(), + (float) getHeight() / (float) renderer.source.getImageHeight()); + } + + @Override + protected void dispatchDraw(Canvas canvas) { + mTextureView.render(); + super.dispatchDraw(canvas); + } + + @Override + public void invalidate() { + super.invalidate(); + mTextureView.invalidate(); + } + + private class TileRenderer implements Renderer { + + private GLES20Canvas mCanvas; + + @Override + public void onSurfaceCreated(GL10 gl, EGLConfig config) { + mCanvas = new GLES20Canvas(); + for (ImageRendererWrapper renderer : mRenderers) { + renderer.image.setModel(renderer.source, renderer.rotation); + } + } + + @Override + public void onSurfaceChanged(GL10 gl, int width, int height) { + mCanvas.setSize(width, height); + for (ImageRendererWrapper renderer : mRenderers) { + renderer.image.setViewSize(width, height); + } + } + + @Override + public void onDrawFrame(GL10 gl) { + mCanvas.clearBuffer(); + synchronized (mLock) { + for (ImageRendererWrapper renderer : mRenderers) { + renderer.image.setModel(renderer.source, renderer.rotation); + renderer.image.setPosition(renderer.centerX, renderer.centerY, renderer.scale); + } + } + for (ImageRendererWrapper renderer : mRenderers) { + renderer.image.draw(mCanvas); + } + } + + } + + private static class ColoredTiles implements TileSource { + private static int[] COLORS = new int[] { + Color.RED, + Color.BLUE, + Color.YELLOW, + Color.GREEN, + Color.CYAN, + Color.MAGENTA, + Color.WHITE, + }; + + private Paint mPaint = new Paint(); + private Canvas mCanvas = new Canvas(); + + @Override + public int getTileSize() { + return 256; + } + + @Override + public int getImageWidth() { + return 16384; + } + + @Override + public int getImageHeight() { + return 8192; + } + + @Override + public Bitmap getTile(int level, int x, int y, Bitmap bitmap) { + int tileSize = getTileSize(); + if (bitmap == null) { + bitmap = Bitmap.createBitmap(tileSize, tileSize, + Bitmap.Config.ARGB_8888); + } + mCanvas.setBitmap(bitmap); + mCanvas.drawColor(COLORS[level]); + mPaint.setColor(Color.BLACK); + mPaint.setTextSize(20); + mPaint.setTextAlign(Align.CENTER); + mCanvas.drawText(x + "x" + y, 128, 128, mPaint); + tileSize <<= level; + x /= tileSize; + y /= tileSize; + mCanvas.drawText(x + "x" + y + " @ " + level, 128, 30, mPaint); + mCanvas.setBitmap(null); + return bitmap; + } + } +} |