diff options
Diffstat (limited to 'src/com/android/photos/views')
-rw-r--r-- | src/com/android/photos/views/BlockingGLTextureView.java | 438 | ||||
-rw-r--r-- | src/com/android/photos/views/GalleryThumbnailView.java | 883 | ||||
-rw-r--r-- | src/com/android/photos/views/HeaderGridView.java | 466 | ||||
-rw-r--r-- | src/com/android/photos/views/SquareImageView.java | 53 | ||||
-rw-r--r-- | src/com/android/photos/views/TiledImageRenderer.java | 825 | ||||
-rw-r--r-- | src/com/android/photos/views/TiledImageView.java | 382 |
6 files changed, 0 insertions, 3047 deletions
diff --git a/src/com/android/photos/views/BlockingGLTextureView.java b/src/com/android/photos/views/BlockingGLTextureView.java deleted file mode 100644 index 8a0505185..000000000 --- a/src/com/android/photos/views/BlockingGLTextureView.java +++ /dev/null @@ -1,438 +0,0 @@ -/* - * 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.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; - -/** - * A TextureView that supports blocking rendering for synchronous drawing - */ -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) { - // Ignore - } - 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[] attribList = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE }; - return egl.eglCreateContext(eglDisplay, eglConfig, EGL10.EGL_NO_CONTEXT, attribList); - } - - /** - * 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) { - // Ignore - } - } - - 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) { - // Ignore - } - } - } - - 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) { - // Ignore - } - } - handleMessageLocked(mExecMsgId); - mExecMsgId = INVALID; - mLock.notify(); - } - mExecMsgId = FINISH; - } - } - } -} diff --git a/src/com/android/photos/views/GalleryThumbnailView.java b/src/com/android/photos/views/GalleryThumbnailView.java deleted file mode 100644 index e5dd6f2ff..000000000 --- a/src/com/android/photos/views/GalleryThumbnailView.java +++ /dev/null @@ -1,883 +0,0 @@ -/* - * 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.content.res.TypedArray; -import android.database.DataSetObserver; -import android.graphics.Canvas; -import android.support.v4.view.MotionEventCompat; -import android.support.v4.view.VelocityTrackerCompat; -import android.support.v4.view.ViewCompat; -import android.support.v4.widget.EdgeEffectCompat; -import android.util.AttributeSet; -import android.util.Log; -import android.util.SparseArray; -import android.view.MotionEvent; -import android.view.VelocityTracker; -import android.view.View; -import android.view.ViewConfiguration; -import android.view.ViewGroup; -import android.widget.ListAdapter; -import android.widget.OverScroller; - -import java.util.ArrayList; - -public class GalleryThumbnailView extends ViewGroup { - - public interface GalleryThumbnailAdapter extends ListAdapter { - /** - * @param position Position to get the intrinsic aspect ratio for - * @return width / height - */ - float getIntrinsicAspectRatio(int position); - } - - private static final String TAG = "GalleryThumbnailView"; - private static final float ASPECT_RATIO = (float) Math.sqrt(1.5f); - private static final int LAND_UNITS = 2; - private static final int PORT_UNITS = 3; - - private GalleryThumbnailAdapter mAdapter; - - private final RecycleBin mRecycler = new RecycleBin(); - - private final AdapterDataSetObserver mObserver = new AdapterDataSetObserver(); - - private boolean mDataChanged; - private int mOldItemCount; - private int mItemCount; - private boolean mHasStableIds; - - private int mFirstPosition; - - private boolean mPopulating; - private boolean mInLayout; - - private int mTouchSlop; - private int mMaximumVelocity; - private int mFlingVelocity; - private float mLastTouchX; - private float mTouchRemainderX; - private int mActivePointerId; - - private static final int TOUCH_MODE_IDLE = 0; - private static final int TOUCH_MODE_DRAGGING = 1; - private static final int TOUCH_MODE_FLINGING = 2; - - private int mTouchMode; - private final VelocityTracker mVelocityTracker = VelocityTracker.obtain(); - private final OverScroller mScroller; - - private final EdgeEffectCompat mLeftEdge; - private final EdgeEffectCompat mRightEdge; - - private int mLargeColumnWidth; - private int mSmallColumnWidth; - private int mLargeColumnUnitCount = 8; - private int mSmallColumnUnitCount = 10; - - public GalleryThumbnailView(Context context) { - this(context, null); - } - - public GalleryThumbnailView(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } - - public GalleryThumbnailView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - - final ViewConfiguration vc = ViewConfiguration.get(context); - mTouchSlop = vc.getScaledTouchSlop(); - mMaximumVelocity = vc.getScaledMaximumFlingVelocity(); - mFlingVelocity = vc.getScaledMinimumFlingVelocity(); - mScroller = new OverScroller(context); - - mLeftEdge = new EdgeEffectCompat(context); - mRightEdge = new EdgeEffectCompat(context); - setWillNotDraw(false); - setClipToPadding(false); - } - - @Override - public void requestLayout() { - if (!mPopulating) { - super.requestLayout(); - } - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - int widthMode = MeasureSpec.getMode(widthMeasureSpec); - int heightMode = MeasureSpec.getMode(heightMeasureSpec); - int widthSize = MeasureSpec.getSize(widthMeasureSpec); - int heightSize = MeasureSpec.getSize(heightMeasureSpec); - - if (widthMode != MeasureSpec.EXACTLY) { - Log.e(TAG, "onMeasure: must have an exact width or match_parent! " + - "Using fallback spec of EXACTLY " + widthSize); - } - if (heightMode != MeasureSpec.EXACTLY) { - Log.e(TAG, "onMeasure: must have an exact height or match_parent! " + - "Using fallback spec of EXACTLY " + heightSize); - } - - setMeasuredDimension(widthSize, heightSize); - - float portSpaces = mLargeColumnUnitCount / PORT_UNITS; - float height = getMeasuredHeight() / portSpaces; - mLargeColumnWidth = (int) (height / ASPECT_RATIO); - portSpaces++; - height = getMeasuredHeight() / portSpaces; - mSmallColumnWidth = (int) (height / ASPECT_RATIO); - } - - @Override - protected void onLayout(boolean changed, int l, int t, int r, int b) { - mInLayout = true; - populate(); - mInLayout = false; - - final int width = r - l; - final int height = b - t; - mLeftEdge.setSize(width, height); - mRightEdge.setSize(width, height); - } - - private void populate() { - if (getWidth() == 0 || getHeight() == 0) { - return; - } - - // TODO: Handle size changing -// final int colCount = mColCount; -// if (mItemTops == null || mItemTops.length != colCount) { -// mItemTops = new int[colCount]; -// mItemBottoms = new int[colCount]; -// final int top = getPaddingTop(); -// final int offset = top + Math.min(mRestoreOffset, 0); -// Arrays.fill(mItemTops, offset); -// Arrays.fill(mItemBottoms, offset); -// mLayoutRecords.clear(); -// if (mInLayout) { -// removeAllViewsInLayout(); -// } else { -// removeAllViews(); -// } -// mRestoreOffset = 0; -// } - - mPopulating = true; - layoutChildren(mDataChanged); - fillRight(mFirstPosition + getChildCount(), 0); - fillLeft(mFirstPosition - 1, 0); - mPopulating = false; - mDataChanged = false; - } - - final void layoutChildren(boolean queryAdapter) { -// TODO -// final int childCount = getChildCount(); -// for (int i = 0; i < childCount; i++) { -// View child = getChildAt(i); -// -// if (child.isLayoutRequested()) { -// final int widthSpec = MeasureSpec.makeMeasureSpec(child.getMeasuredWidth(), MeasureSpec.EXACTLY); -// final int heightSpec = MeasureSpec.makeMeasureSpec(child.getMeasuredHeight(), MeasureSpec.EXACTLY); -// child.measure(widthSpec, heightSpec); -// child.layout(child.getLeft(), child.getTop(), child.getRight(), child.getBottom()); -// } -// -// int childTop = mItemBottoms[col] > Integer.MIN_VALUE ? -// mItemBottoms[col] + mItemMargin : child.getTop(); -// if (span > 1) { -// int lowest = childTop; -// for (int j = col + 1; j < col + span; j++) { -// final int bottom = mItemBottoms[j] + mItemMargin; -// if (bottom > lowest) { -// lowest = bottom; -// } -// } -// childTop = lowest; -// } -// final int childHeight = child.getMeasuredHeight(); -// final int childBottom = childTop + childHeight; -// final int childLeft = paddingLeft + col * (colWidth + itemMargin); -// final int childRight = childLeft + child.getMeasuredWidth(); -// child.layout(childLeft, childTop, childRight, childBottom); -// } - } - - /** - * Obtain the view and add it to our list of children. The view can be made - * fresh, converted from an unused view, or used as is if it was in the - * recycle bin. - * - * @param startPosition Logical position in the list to start from - * @param x Left or right edge of the view to add - * @param forward If true, align left edge to x and increase position. - * If false, align right edge to x and decrease position. - * @return Number of views added - */ - private int makeAndAddColumn(int startPosition, int x, boolean forward) { - int columnWidth = mLargeColumnWidth; - int addViews = 0; - for (int remaining = mLargeColumnUnitCount, i = 0; - remaining > 0 && startPosition + i >= 0 && startPosition + i < mItemCount; - i += forward ? 1 : -1, addViews++) { - if (mAdapter.getIntrinsicAspectRatio(startPosition + i) >= 1f) { - // landscape - remaining -= LAND_UNITS; - } else { - // portrait - remaining -= PORT_UNITS; - if (remaining < 0) { - remaining += (mSmallColumnUnitCount - mLargeColumnUnitCount); - columnWidth = mSmallColumnWidth; - } - } - } - int nextTop = 0; - for (int i = 0; i < addViews; i++) { - int position = startPosition + (forward ? i : -i); - View child = obtainView(position, null); - if (child.getParent() != this) { - if (mInLayout) { - addViewInLayout(child, forward ? -1 : 0, child.getLayoutParams()); - } else { - addView(child, forward ? -1 : 0); - } - } - int heightSize = (int) (.5f + (mAdapter.getIntrinsicAspectRatio(position) >= 1f - ? columnWidth / ASPECT_RATIO - : columnWidth * ASPECT_RATIO)); - int heightSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY); - int widthSpec = MeasureSpec.makeMeasureSpec(columnWidth, MeasureSpec.EXACTLY); - child.measure(widthSpec, heightSpec); - int childLeft = forward ? x : x - columnWidth; - child.layout(childLeft, nextTop, childLeft + columnWidth, nextTop + heightSize); - nextTop += heightSize; - } - return addViews; - } - - @Override - public boolean onInterceptTouchEvent(MotionEvent ev) { - mVelocityTracker.addMovement(ev); - final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; - switch (action) { - case MotionEvent.ACTION_DOWN: - mVelocityTracker.clear(); - mScroller.abortAnimation(); - mLastTouchX = ev.getX(); - mActivePointerId = MotionEventCompat.getPointerId(ev, 0); - mTouchRemainderX = 0; - if (mTouchMode == TOUCH_MODE_FLINGING) { - // Catch! - mTouchMode = TOUCH_MODE_DRAGGING; - return true; - } - break; - - case MotionEvent.ACTION_MOVE: { - final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId); - if (index < 0) { - Log.e(TAG, "onInterceptTouchEvent could not find pointer with id " + - mActivePointerId + " - did StaggeredGridView receive an inconsistent " + - "event stream?"); - return false; - } - final float x = MotionEventCompat.getX(ev, index); - final float dx = x - mLastTouchX + mTouchRemainderX; - final int deltaY = (int) dx; - mTouchRemainderX = dx - deltaY; - - if (Math.abs(dx) > mTouchSlop) { - mTouchMode = TOUCH_MODE_DRAGGING; - return true; - } - } - } - - return false; - } - - @Override - public boolean onTouchEvent(MotionEvent ev) { - mVelocityTracker.addMovement(ev); - final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; - switch (action) { - case MotionEvent.ACTION_DOWN: - mVelocityTracker.clear(); - mScroller.abortAnimation(); - mLastTouchX = ev.getX(); - mActivePointerId = MotionEventCompat.getPointerId(ev, 0); - mTouchRemainderX = 0; - break; - - case MotionEvent.ACTION_MOVE: { - final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId); - if (index < 0) { - Log.e(TAG, "onInterceptTouchEvent could not find pointer with id " + - mActivePointerId + " - did StaggeredGridView receive an inconsistent " + - "event stream?"); - return false; - } - final float x = MotionEventCompat.getX(ev, index); - final float dx = x - mLastTouchX + mTouchRemainderX; - final int deltaX = (int) dx; - mTouchRemainderX = dx - deltaX; - - if (Math.abs(dx) > mTouchSlop) { - mTouchMode = TOUCH_MODE_DRAGGING; - } - - if (mTouchMode == TOUCH_MODE_DRAGGING) { - mLastTouchX = x; - - if (!trackMotionScroll(deltaX, true)) { - // Break fling velocity if we impacted an edge. - mVelocityTracker.clear(); - } - } - } break; - - case MotionEvent.ACTION_CANCEL: - mTouchMode = TOUCH_MODE_IDLE; - break; - - case MotionEvent.ACTION_UP: { - mVelocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); - final float velocity = VelocityTrackerCompat.getXVelocity(mVelocityTracker, - mActivePointerId); - if (Math.abs(velocity) > mFlingVelocity) { // TODO - mTouchMode = TOUCH_MODE_FLINGING; - mScroller.fling(0, 0, (int) velocity, 0, - Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0); - mLastTouchX = 0; - ViewCompat.postInvalidateOnAnimation(this); - } else { - mTouchMode = TOUCH_MODE_IDLE; - } - - } break; - } - return true; - } - - /** - * - * @param deltaX Pixels that content should move by - * @return true if the movement completed, false if it was stopped prematurely. - */ - private boolean trackMotionScroll(int deltaX, boolean allowOverScroll) { - final boolean contentFits = contentFits(); - final int allowOverhang = Math.abs(deltaX); - - final int overScrolledBy; - final int movedBy; - if (!contentFits) { - final int overhang; - final boolean up; - mPopulating = true; - if (deltaX > 0) { - overhang = fillLeft(mFirstPosition - 1, allowOverhang); - up = true; - } else { - overhang = fillRight(mFirstPosition + getChildCount(), allowOverhang); - up = false; - } - movedBy = Math.min(overhang, allowOverhang); - offsetChildren(up ? movedBy : -movedBy); - recycleOffscreenViews(); - mPopulating = false; - overScrolledBy = allowOverhang - overhang; - } else { - overScrolledBy = allowOverhang; - movedBy = 0; - } - - if (allowOverScroll) { - final int overScrollMode = ViewCompat.getOverScrollMode(this); - - if (overScrollMode == ViewCompat.OVER_SCROLL_ALWAYS || - (overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS && !contentFits)) { - - if (overScrolledBy > 0) { - EdgeEffectCompat edge = deltaX > 0 ? mLeftEdge : mRightEdge; - edge.onPull((float) Math.abs(deltaX) / getWidth()); - ViewCompat.postInvalidateOnAnimation(this); - } - } - } - - return deltaX == 0 || movedBy != 0; - } - - /** - * Important: this method will leave offscreen views attached if they - * are required to maintain the invariant that child view with index i - * is always the view corresponding to position mFirstPosition + i. - */ - private void recycleOffscreenViews() { - final int height = getHeight(); - final int clearAbove = 0; - final int clearBelow = height; - for (int i = getChildCount() - 1; i >= 0; i--) { - final View child = getChildAt(i); - if (child.getTop() <= clearBelow) { - // There may be other offscreen views, but we need to maintain - // the invariant documented above. - break; - } - - if (mInLayout) { - removeViewsInLayout(i, 1); - } else { - removeViewAt(i); - } - - mRecycler.addScrap(child); - } - - while (getChildCount() > 0) { - final View child = getChildAt(0); - if (child.getBottom() >= clearAbove) { - // There may be other offscreen views, but we need to maintain - // the invariant documented above. - break; - } - - if (mInLayout) { - removeViewsInLayout(0, 1); - } else { - removeViewAt(0); - } - - mRecycler.addScrap(child); - mFirstPosition++; - } - } - - final void offsetChildren(int offset) { - final int childCount = getChildCount(); - for (int i = 0; i < childCount; i++) { - final View child = getChildAt(i); - child.layout(child.getLeft() + offset, child.getTop(), - child.getRight() + offset, child.getBottom()); - } - } - - private boolean contentFits() { - final int childCount = getChildCount(); - if (childCount == 0) return true; - if (childCount != mItemCount) return false; - - return getChildAt(0).getLeft() >= getPaddingLeft() && - getChildAt(childCount - 1).getRight() <= getWidth() - getPaddingRight(); - } - - private void recycleAllViews() { - for (int i = 0; i < getChildCount(); i++) { - mRecycler.addScrap(getChildAt(i)); - } - - if (mInLayout) { - removeAllViewsInLayout(); - } else { - removeAllViews(); - } - } - - private int fillRight(int pos, int overhang) { - int end = (getRight() - getLeft()) + overhang; - - int nextLeft = getChildCount() == 0 ? 0 : getChildAt(getChildCount() - 1).getRight(); - while (nextLeft < end && pos < mItemCount) { - pos += makeAndAddColumn(pos, nextLeft, true); - nextLeft = getChildAt(getChildCount() - 1).getRight(); - } - final int gridRight = getWidth() - getPaddingRight(); - return getChildAt(getChildCount() - 1).getRight() - gridRight; - } - - private int fillLeft(int pos, int overhang) { - int end = getPaddingLeft() - overhang; - - int nextRight = getChildAt(0).getLeft(); - while (nextRight > end && pos >= 0) { - pos -= makeAndAddColumn(pos, nextRight, false); - nextRight = getChildAt(0).getLeft(); - } - - mFirstPosition = pos + 1; - return getPaddingLeft() - getChildAt(0).getLeft(); - } - - @Override - public void computeScroll() { - if (mScroller.computeScrollOffset()) { - final int x = mScroller.getCurrX(); - final int dx = (int) (x - mLastTouchX); - mLastTouchX = x; - final boolean stopped = !trackMotionScroll(dx, false); - - if (!stopped && !mScroller.isFinished()) { - ViewCompat.postInvalidateOnAnimation(this); - } else { - if (stopped) { - final int overScrollMode = ViewCompat.getOverScrollMode(this); - if (overScrollMode != ViewCompat.OVER_SCROLL_NEVER) { - final EdgeEffectCompat edge; - if (dx > 0) { - edge = mLeftEdge; - } else { - edge = mRightEdge; - } - edge.onAbsorb(Math.abs((int) mScroller.getCurrVelocity())); - ViewCompat.postInvalidateOnAnimation(this); - } - mScroller.abortAnimation(); - } - mTouchMode = TOUCH_MODE_IDLE; - } - } - } - - @Override - public void draw(Canvas canvas) { - super.draw(canvas); - - if (!mLeftEdge.isFinished()) { - final int restoreCount = canvas.save(); - final int height = getHeight() - getPaddingTop() - getPaddingBottom(); - - canvas.rotate(270); - canvas.translate(-height + getPaddingTop(), 0); - mLeftEdge.setSize(height, getWidth()); - if (mLeftEdge.draw(canvas)) { - postInvalidateOnAnimation(); - } - canvas.restoreToCount(restoreCount); - } - if (!mRightEdge.isFinished()) { - final int restoreCount = canvas.save(); - final int width = getWidth(); - final int height = getHeight() - getPaddingTop() - getPaddingBottom(); - - canvas.rotate(90); - canvas.translate(-getPaddingTop(), width); - mRightEdge.setSize(height, width); - if (mRightEdge.draw(canvas)) { - postInvalidateOnAnimation(); - } - canvas.restoreToCount(restoreCount); - } - } - - /** - * Obtain a populated view from the adapter. If optScrap is non-null and is not - * reused it will be placed in the recycle bin. - * - * @param position position to get view for - * @param optScrap Optional scrap view; will be reused if possible - * @return A new view, a recycled view from mRecycler, or optScrap - */ - private final View obtainView(int position, View optScrap) { - View view = mRecycler.getTransientStateView(position); - if (view != null) { - return view; - } - - // Reuse optScrap if it's of the right type (and not null) - final int optType = optScrap != null ? - ((LayoutParams) optScrap.getLayoutParams()).viewType : -1; - final int positionViewType = mAdapter.getItemViewType(position); - final View scrap = optType == positionViewType ? - optScrap : mRecycler.getScrapView(positionViewType); - - view = mAdapter.getView(position, scrap, this); - - if (view != scrap && scrap != null) { - // The adapter didn't use it; put it back. - mRecycler.addScrap(scrap); - } - - ViewGroup.LayoutParams lp = view.getLayoutParams(); - - if (view.getParent() != this) { - if (lp == null) { - lp = generateDefaultLayoutParams(); - } else if (!checkLayoutParams(lp)) { - lp = generateLayoutParams(lp); - } - view.setLayoutParams(lp); - } - - final LayoutParams sglp = (LayoutParams) lp; - sglp.position = position; - sglp.viewType = positionViewType; - - return view; - } - - public GalleryThumbnailAdapter getAdapter() { - return mAdapter; - } - - public void setAdapter(GalleryThumbnailAdapter adapter) { - if (mAdapter != null) { - mAdapter.unregisterDataSetObserver(mObserver); - } - // TODO: If the new adapter says that there are stable IDs, remove certain layout records - // and onscreen views if they have changed instead of removing all of the state here. - clearAllState(); - mAdapter = adapter; - mDataChanged = true; - mOldItemCount = mItemCount = adapter != null ? adapter.getCount() : 0; - if (adapter != null) { - adapter.registerDataSetObserver(mObserver); - mRecycler.setViewTypeCount(adapter.getViewTypeCount()); - mHasStableIds = adapter.hasStableIds(); - } else { - mHasStableIds = false; - } - populate(); - } - - /** - * Clear all state because the grid will be used for a completely different set of data. - */ - private void clearAllState() { - // Clear all layout records and views - removeAllViews(); - - // Reset to the top of the grid - mFirstPosition = 0; - - // Clear recycler because there could be different view types now - mRecycler.clear(); - } - - @Override - protected LayoutParams generateDefaultLayoutParams() { - return new LayoutParams(LayoutParams.WRAP_CONTENT); - } - - @Override - protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { - return new LayoutParams(lp); - } - - @Override - protected boolean checkLayoutParams(ViewGroup.LayoutParams lp) { - return lp instanceof LayoutParams; - } - - @Override - public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { - return new LayoutParams(getContext(), attrs); - } - - public static class LayoutParams extends ViewGroup.LayoutParams { - private static final int[] LAYOUT_ATTRS = new int[] { - android.R.attr.layout_span - }; - - private static final int SPAN_INDEX = 0; - - /** - * The number of columns this item should span - */ - public int span = 1; - - /** - * Item position this view represents - */ - int position; - - /** - * Type of this view as reported by the adapter - */ - int viewType; - - /** - * The column this view is occupying - */ - int column; - - /** - * The stable ID of the item this view displays - */ - long id = -1; - - public LayoutParams(int height) { - super(MATCH_PARENT, height); - - if (this.height == MATCH_PARENT) { - Log.w(TAG, "Constructing LayoutParams with height MATCH_PARENT - " + - "impossible! Falling back to WRAP_CONTENT"); - this.height = WRAP_CONTENT; - } - } - - public LayoutParams(Context c, AttributeSet attrs) { - super(c, attrs); - - if (this.width != MATCH_PARENT) { - Log.w(TAG, "Inflation setting LayoutParams width to " + this.width + - " - must be MATCH_PARENT"); - this.width = MATCH_PARENT; - } - if (this.height == MATCH_PARENT) { - Log.w(TAG, "Inflation setting LayoutParams height to MATCH_PARENT - " + - "impossible! Falling back to WRAP_CONTENT"); - this.height = WRAP_CONTENT; - } - - TypedArray a = c.obtainStyledAttributes(attrs, LAYOUT_ATTRS); - span = a.getInteger(SPAN_INDEX, 1); - a.recycle(); - } - - public LayoutParams(ViewGroup.LayoutParams other) { - super(other); - - if (this.width != MATCH_PARENT) { - Log.w(TAG, "Constructing LayoutParams with width " + this.width + - " - must be MATCH_PARENT"); - this.width = MATCH_PARENT; - } - if (this.height == MATCH_PARENT) { - Log.w(TAG, "Constructing LayoutParams with height MATCH_PARENT - " + - "impossible! Falling back to WRAP_CONTENT"); - this.height = WRAP_CONTENT; - } - } - } - - private class RecycleBin { - private ArrayList<View>[] mScrapViews; - private int mViewTypeCount; - private int mMaxScrap; - - private SparseArray<View> mTransientStateViews; - - public void setViewTypeCount(int viewTypeCount) { - if (viewTypeCount < 1) { - throw new IllegalArgumentException("Must have at least one view type (" + - viewTypeCount + " types reported)"); - } - if (viewTypeCount == mViewTypeCount) { - return; - } - - ArrayList<View>[] scrapViews = new ArrayList[viewTypeCount]; - for (int i = 0; i < viewTypeCount; i++) { - scrapViews[i] = new ArrayList<View>(); - } - mViewTypeCount = viewTypeCount; - mScrapViews = scrapViews; - } - - public void clear() { - final int typeCount = mViewTypeCount; - for (int i = 0; i < typeCount; i++) { - mScrapViews[i].clear(); - } - if (mTransientStateViews != null) { - mTransientStateViews.clear(); - } - } - - public void clearTransientViews() { - if (mTransientStateViews != null) { - mTransientStateViews.clear(); - } - } - - public void addScrap(View v) { - final LayoutParams lp = (LayoutParams) v.getLayoutParams(); - if (ViewCompat.hasTransientState(v)) { - if (mTransientStateViews == null) { - mTransientStateViews = new SparseArray<View>(); - } - mTransientStateViews.put(lp.position, v); - return; - } - - final int childCount = getChildCount(); - if (childCount > mMaxScrap) { - mMaxScrap = childCount; - } - - ArrayList<View> scrap = mScrapViews[lp.viewType]; - if (scrap.size() < mMaxScrap) { - scrap.add(v); - } - } - - public View getTransientStateView(int position) { - if (mTransientStateViews == null) { - return null; - } - - final View result = mTransientStateViews.get(position); - if (result != null) { - mTransientStateViews.remove(position); - } - return result; - } - - public View getScrapView(int type) { - ArrayList<View> scrap = mScrapViews[type]; - if (scrap.isEmpty()) { - return null; - } - - final int index = scrap.size() - 1; - final View result = scrap.get(index); - scrap.remove(index); - return result; - } - } - - private class AdapterDataSetObserver extends DataSetObserver { - @Override - public void onChanged() { - mDataChanged = true; - mOldItemCount = mItemCount; - mItemCount = mAdapter.getCount(); - - // TODO: Consider matching these back up if we have stable IDs. - mRecycler.clearTransientViews(); - - if (!mHasStableIds) { - recycleAllViews(); - } - - // TODO: consider repopulating in a deferred runnable instead - // (so that successive changes may still be batched) - requestLayout(); - } - - @Override - public void onInvalidated() { - } - } -} diff --git a/src/com/android/photos/views/HeaderGridView.java b/src/com/android/photos/views/HeaderGridView.java deleted file mode 100644 index 45a5eaf73..000000000 --- a/src/com/android/photos/views/HeaderGridView.java +++ /dev/null @@ -1,466 +0,0 @@ -/* - * 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.database.DataSetObservable; -import android.database.DataSetObserver; -import android.util.AttributeSet; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.Filter; -import android.widget.Filterable; -import android.widget.FrameLayout; -import android.widget.GridView; -import android.widget.ListAdapter; -import android.widget.WrapperListAdapter; - -import java.util.ArrayList; - -/** - * A {@link GridView} that supports adding header rows in a - * very similar way to {@link ListView}. - * See {@link HeaderGridView#addHeaderView(View, Object, boolean)} - */ -public class HeaderGridView extends GridView { - private static final String TAG = "HeaderGridView"; - - /** - * A class that represents a fixed view in a list, for example a header at the top - * or a footer at the bottom. - */ - private static class FixedViewInfo { - /** The view to add to the grid */ - public View view; - public ViewGroup viewContainer; - /** The data backing the view. This is returned from {@link ListAdapter#getItem(int)}. */ - public Object data; - /** <code>true</code> if the fixed view should be selectable in the grid */ - public boolean isSelectable; - } - - private ArrayList<FixedViewInfo> mHeaderViewInfos = new ArrayList<FixedViewInfo>(); - - private void initHeaderGridView() { - super.setClipChildren(false); - } - - public HeaderGridView(Context context) { - super(context); - initHeaderGridView(); - } - - public HeaderGridView(Context context, AttributeSet attrs) { - super(context, attrs); - initHeaderGridView(); - } - - public HeaderGridView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - initHeaderGridView(); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - ListAdapter adapter = getAdapter(); - if (adapter != null && adapter instanceof HeaderViewGridAdapter) { - ((HeaderViewGridAdapter) adapter).setNumColumns(getNumColumns()); - } - } - - @Override - public void setClipChildren(boolean clipChildren) { - // Ignore, since the header rows depend on not being clipped - } - - /** - * Add a fixed view to appear at the top of the grid. If addHeaderView is - * called more than once, the views will appear in the order they were - * added. Views added using this call can take focus if they want. - * <p> - * NOTE: Call this before calling setAdapter. This is so HeaderGridView can wrap - * the supplied cursor with one that will also account for header views. - * - * @param v The view to add. - * @param data Data to associate with this view - * @param isSelectable whether the item is selectable - */ - public void addHeaderView(View v, Object data, boolean isSelectable) { - ListAdapter adapter = getAdapter(); - - if (adapter != null && ! (adapter instanceof HeaderViewGridAdapter)) { - throw new IllegalStateException( - "Cannot add header view to grid -- setAdapter has already been called."); - } - - FixedViewInfo info = new FixedViewInfo(); - FrameLayout fl = new FullWidthFixedViewLayout(getContext()); - fl.addView(v); - info.view = v; - info.viewContainer = fl; - info.data = data; - info.isSelectable = isSelectable; - mHeaderViewInfos.add(info); - - // in the case of re-adding a header view, or adding one later on, - // we need to notify the observer - if (adapter != null) { - ((HeaderViewGridAdapter) adapter).notifyDataSetChanged(); - } - } - - /** - * Add a fixed view to appear at the top of the grid. If addHeaderView is - * called more than once, the views will appear in the order they were - * added. Views added using this call can take focus if they want. - * <p> - * NOTE: Call this before calling setAdapter. This is so HeaderGridView can wrap - * the supplied cursor with one that will also account for header views. - * - * @param v The view to add. - */ - public void addHeaderView(View v) { - addHeaderView(v, null, true); - } - - public int getHeaderViewCount() { - return mHeaderViewInfos.size(); - } - - /** - * Removes a previously-added header view. - * - * @param v The view to remove - * @return true if the view was removed, false if the view was not a header - * view - */ - public boolean removeHeaderView(View v) { - if (mHeaderViewInfos.size() > 0) { - boolean result = false; - ListAdapter adapter = getAdapter(); - if (adapter != null && ((HeaderViewGridAdapter) adapter).removeHeader(v)) { - result = true; - } - removeFixedViewInfo(v, mHeaderViewInfos); - return result; - } - return false; - } - - private void removeFixedViewInfo(View v, ArrayList<FixedViewInfo> where) { - int len = where.size(); - for (int i = 0; i < len; ++i) { - FixedViewInfo info = where.get(i); - if (info.view == v) { - where.remove(i); - break; - } - } - } - - @Override - public void setAdapter(ListAdapter adapter) { - if (mHeaderViewInfos.size() > 0) { - HeaderViewGridAdapter hadapter = new HeaderViewGridAdapter(mHeaderViewInfos, adapter); - int numColumns = getNumColumns(); - if (numColumns > 1) { - hadapter.setNumColumns(numColumns); - } - super.setAdapter(hadapter); - } else { - super.setAdapter(adapter); - } - } - - private class FullWidthFixedViewLayout extends FrameLayout { - public FullWidthFixedViewLayout(Context context) { - super(context); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - int targetWidth = HeaderGridView.this.getMeasuredWidth() - - HeaderGridView.this.getPaddingLeft() - - HeaderGridView.this.getPaddingRight(); - widthMeasureSpec = MeasureSpec.makeMeasureSpec(targetWidth, - MeasureSpec.getMode(widthMeasureSpec)); - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - } - } - - /** - * ListAdapter used when a HeaderGridView has header views. This ListAdapter - * wraps another one and also keeps track of the header views and their - * associated data objects. - *<p>This is intended as a base class; you will probably not need to - * use this class directly in your own code. - */ - private static class HeaderViewGridAdapter implements WrapperListAdapter, Filterable { - - // This is used to notify the container of updates relating to number of columns - // or headers changing, which changes the number of placeholders needed - private final DataSetObservable mDataSetObservable = new DataSetObservable(); - - private final ListAdapter mAdapter; - private int mNumColumns = 1; - - // This ArrayList is assumed to NOT be null. - ArrayList<FixedViewInfo> mHeaderViewInfos; - - boolean mAreAllFixedViewsSelectable; - - private final boolean mIsFilterable; - - public HeaderViewGridAdapter(ArrayList<FixedViewInfo> headerViewInfos, ListAdapter adapter) { - mAdapter = adapter; - mIsFilterable = adapter instanceof Filterable; - - if (headerViewInfos == null) { - throw new IllegalArgumentException("headerViewInfos cannot be null"); - } - mHeaderViewInfos = headerViewInfos; - - mAreAllFixedViewsSelectable = areAllListInfosSelectable(mHeaderViewInfos); - } - - public int getHeadersCount() { - return mHeaderViewInfos.size(); - } - - @Override - public boolean isEmpty() { - return (mAdapter == null || mAdapter.isEmpty()) && getHeadersCount() == 0; - } - - public void setNumColumns(int numColumns) { - if (numColumns < 1) { - throw new IllegalArgumentException("Number of columns must be 1 or more"); - } - if (mNumColumns != numColumns) { - mNumColumns = numColumns; - notifyDataSetChanged(); - } - } - - private boolean areAllListInfosSelectable(ArrayList<FixedViewInfo> infos) { - if (infos != null) { - for (FixedViewInfo info : infos) { - if (!info.isSelectable) { - return false; - } - } - } - return true; - } - - public boolean removeHeader(View v) { - for (int i = 0; i < mHeaderViewInfos.size(); i++) { - FixedViewInfo info = mHeaderViewInfos.get(i); - if (info.view == v) { - mHeaderViewInfos.remove(i); - - mAreAllFixedViewsSelectable = areAllListInfosSelectable(mHeaderViewInfos); - - mDataSetObservable.notifyChanged(); - return true; - } - } - - return false; - } - - @Override - public int getCount() { - if (mAdapter != null) { - return getHeadersCount() * mNumColumns + mAdapter.getCount(); - } else { - return getHeadersCount() * mNumColumns; - } - } - - @Override - public boolean areAllItemsEnabled() { - if (mAdapter != null) { - return mAreAllFixedViewsSelectable && mAdapter.areAllItemsEnabled(); - } else { - return true; - } - } - - @Override - public boolean isEnabled(int position) { - // Header (negative positions will throw an ArrayIndexOutOfBoundsException) - int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns; - if (position < numHeadersAndPlaceholders) { - return (position % mNumColumns == 0) - && mHeaderViewInfos.get(position / mNumColumns).isSelectable; - } - - // Adapter - final int adjPosition = position - numHeadersAndPlaceholders; - int adapterCount = 0; - if (mAdapter != null) { - adapterCount = mAdapter.getCount(); - if (adjPosition < adapterCount) { - return mAdapter.isEnabled(adjPosition); - } - } - - throw new ArrayIndexOutOfBoundsException(position); - } - - @Override - public Object getItem(int position) { - // Header (negative positions will throw an ArrayIndexOutOfBoundsException) - int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns; - if (position < numHeadersAndPlaceholders) { - if (position % mNumColumns == 0) { - return mHeaderViewInfos.get(position / mNumColumns).data; - } - return null; - } - - // Adapter - final int adjPosition = position - numHeadersAndPlaceholders; - int adapterCount = 0; - if (mAdapter != null) { - adapterCount = mAdapter.getCount(); - if (adjPosition < adapterCount) { - return mAdapter.getItem(adjPosition); - } - } - - throw new ArrayIndexOutOfBoundsException(position); - } - - @Override - public long getItemId(int position) { - int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns; - if (mAdapter != null && position >= numHeadersAndPlaceholders) { - int adjPosition = position - numHeadersAndPlaceholders; - int adapterCount = mAdapter.getCount(); - if (adjPosition < adapterCount) { - return mAdapter.getItemId(adjPosition); - } - } - return -1; - } - - @Override - public boolean hasStableIds() { - if (mAdapter != null) { - return mAdapter.hasStableIds(); - } - return false; - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - // Header (negative positions will throw an ArrayIndexOutOfBoundsException) - int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns ; - if (position < numHeadersAndPlaceholders) { - View headerViewContainer = mHeaderViewInfos - .get(position / mNumColumns).viewContainer; - if (position % mNumColumns == 0) { - return headerViewContainer; - } else { - if (convertView == null) { - convertView = new View(parent.getContext()); - } - // We need to do this because GridView uses the height of the last item - // in a row to determine the height for the entire row. - convertView.setVisibility(View.INVISIBLE); - convertView.setMinimumHeight(headerViewContainer.getHeight()); - return convertView; - } - } - - // Adapter - final int adjPosition = position - numHeadersAndPlaceholders; - int adapterCount = 0; - if (mAdapter != null) { - adapterCount = mAdapter.getCount(); - if (adjPosition < adapterCount) { - return mAdapter.getView(adjPosition, convertView, parent); - } - } - - throw new ArrayIndexOutOfBoundsException(position); - } - - @Override - public int getItemViewType(int position) { - int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns; - if (position < numHeadersAndPlaceholders && (position % mNumColumns != 0)) { - // Placeholders get the last view type number - return mAdapter != null ? mAdapter.getViewTypeCount() : 1; - } - if (mAdapter != null && position >= numHeadersAndPlaceholders) { - int adjPosition = position - numHeadersAndPlaceholders; - int adapterCount = mAdapter.getCount(); - if (adjPosition < adapterCount) { - return mAdapter.getItemViewType(adjPosition); - } - } - - return AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER; - } - - @Override - public int getViewTypeCount() { - if (mAdapter != null) { - return mAdapter.getViewTypeCount() + 1; - } - return 2; - } - - @Override - public void registerDataSetObserver(DataSetObserver observer) { - mDataSetObservable.registerObserver(observer); - if (mAdapter != null) { - mAdapter.registerDataSetObserver(observer); - } - } - - @Override - public void unregisterDataSetObserver(DataSetObserver observer) { - mDataSetObservable.unregisterObserver(observer); - if (mAdapter != null) { - mAdapter.unregisterDataSetObserver(observer); - } - } - - @Override - public Filter getFilter() { - if (mIsFilterable) { - return ((Filterable) mAdapter).getFilter(); - } - return null; - } - - @Override - public ListAdapter getWrappedAdapter() { - return mAdapter; - } - - public void notifyDataSetChanged() { - mDataSetObservable.notifyChanged(); - } - } -} diff --git a/src/com/android/photos/views/SquareImageView.java b/src/com/android/photos/views/SquareImageView.java deleted file mode 100644 index 14eff1077..000000000 --- a/src/com/android/photos/views/SquareImageView.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.util.AttributeSet; -import android.widget.ImageView; - - -public class SquareImageView extends ImageView { - - public SquareImageView(Context context) { - super(context); - } - - public SquareImageView(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public SquareImageView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - int widthMode = MeasureSpec.getMode(widthMeasureSpec); - int heightMode = MeasureSpec.getMode(heightMeasureSpec); - if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) { - int width = MeasureSpec.getSize(widthMeasureSpec); - int height = width; - if (heightMode == MeasureSpec.AT_MOST) { - height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec)); - } - setMeasuredDimension(width, height); - } else { - super.onMeasure(widthMeasureSpec, heightMeasureSpec); - } - } -} diff --git a/src/com/android/photos/views/TiledImageRenderer.java b/src/com/android/photos/views/TiledImageRenderer.java deleted file mode 100644 index c4e493b34..000000000 --- a/src/com/android/photos/views/TiledImageRenderer.java +++ /dev/null @@ -1,825 +0,0 @@ -/* - * 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.util.Pools.Pool; -import android.util.Pools.SynchronizedPool; -import android.view.View; -import android.view.WindowManager; - -import com.android.gallery3d.common.Utils; -import com.android.gallery3d.glrenderer.BasicTexture; -import com.android.gallery3d.glrenderer.GLCanvas; -import com.android.gallery3d.glrenderer.UploadedTexture; - -/** - * Handles laying out, decoding, and drawing of tiles in GL - */ -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 Pool<Bitmap> sTilePool = new SynchronizedPool<Bitmap>(64); - - // TILE_SIZE must be 2^N - private int mTileSize; - - private TileSource mModel; - private BasicTexture mPreview; - 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; - - /** - * Interface for providing tiles to a {@link TiledImageRenderer} - */ - public static interface TileSource { - - /** - * If the source does not care about the tile size, it should use - * {@link TiledImageRenderer#suggestedTileSize(Context)} - */ - public int getTileSize(); - public int getImageWidth(); - public int getImageHeight(); - public int getRotation(); - - /** - * Return a Preview image if available. This will be used as the base layer - * if higher res tiles are not yet available - */ - public BasicTexture getPreview(); - - /** - * 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; - } - } - - private void calculateLevelCount() { - if (mPreview != null) { - mLevelCount = Math.max(0, Utils.ceilLog2( - mImageWidth / (float) mPreview.getWidth())); - } else { - int levels = 1; - int maxDim = Math.max(mImageWidth, mImageHeight); - int t = mTileSize; - while (t < maxDim) { - t <<= 1; - levels++; - } - mLevelCount = levels; - } - } - - public void notifyModelInvalidated() { - invalidateTiles(); - if (mModel == null) { - mImageWidth = 0; - mImageHeight = 0; - mLevelCount = 0; - mPreview = null; - } else { - mImageWidth = mModel.getImageWidth(); - mImageHeight = mModel.getImageHeight(); - mPreview = mModel.getPreview(); - mTileSize = mModel.getTileSize(); - calculateLevelCount(); - } - mLayoutTiles = true; - } - - 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; - } - - // 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(xx): 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; - - mTileDecoder.finishAndWait(); - 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); - - while (sTilePool.acquire() != null) {} - } - - public boolean 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); - } - } - } else if (mPreview != null) { - mPreview.draw(canvas, mOffsetX, mOffsetY, - Math.round(mImageWidth * mScale), - Math.round(mImageHeight * mScale)); - } - } finally { - if (flags != 0) { - canvas.restore(); - } - } - - if (mRenderComplete) { - if (!mBackgroundTileUploaded) { - uploadBackgroundTiles(canvas); - } - } else { - invalidate(); - } - return mRenderComplete || mPreview != null; - } - - 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 queueForDecode(Tile tile) { - synchronized (mQueueLock) { - if (tile.mTileState == STATE_ACTIVATED) { - tile.mTileState = STATE_IN_QUEUE; - if (mDecodeQueue.push(tile)) { - mQueueLock.notifyAll(); - } - } - } - } - - private void decodeTile(Tile tile) { - synchronized (mQueueLock) { - if (tile.mTileState != STATE_IN_QUEUE) { - return; - } - tile.mTileState = STATE_DECODING; - } - boolean decodeComplete = tile.decode(); - synchronized (mQueueLock) { - if (tile.mTileState == STATE_RECYCLING) { - tile.mTileState = STATE_RECYCLED; - if (tile.mDecodedTile != null) { - sTilePool.release(tile.mDecodedTile); - tile.mDecodedTile = null; - } - mRecycledQueue.push(tile); - return; - } - tile.mTileState = decodeComplete ? STATE_DECODED : STATE_DECODE_FAIL; - if (!decodeComplete) { - return; - } - mUploadQueue.push(tile); - } - invalidate(); - } - - 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) { - sTilePool.release(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()) { - if (tile.mTileState == STATE_DECODED) { - tile.updateContent(canvas); - --quota; - } else { - Log.w(TAG, "Tile in upload queue has invalid state: " + tile.mTileState); - } - } - } - 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); - } - } - if (drawTile(tile, canvas, source, target)) { - return; - } - } - if (mPreview != null) { - int size = mTileSize << level; - float scaleX = (float) mPreview.getWidth() / mImageWidth; - float scaleY = (float) mPreview.getHeight() / mImageHeight; - source.set(tx * scaleX, ty * scaleY, (tx + size) * scaleX, - (ty + size) * scaleY); - canvas.drawTexture(mPreview, 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) { - sTilePool.release(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.acquire(); - if (reuse != null && reuse.getWidth() != mTileSize) { - reuse = null; - } - 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) { - if (contains(tile)) { - Log.w(TAG, "Attempting to add a tile already in the queue!"); - return false; - } - boolean wasEmpty = mHead == null; - tile.mNext = mHead; - mHead = tile; - return wasEmpty; - } - - private boolean contains(Tile tile) { - Tile other = mHead; - while (other != null) { - if (other == tile) { - return true; - } - other = other.mNext; - } - return false; - } - - 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(); - decodeTile(tile); - } - } catch (InterruptedException ex) { - // We were finished - } - } - - } -} diff --git a/src/com/android/photos/views/TiledImageView.java b/src/com/android/photos/views/TiledImageView.java deleted file mode 100644 index 8bc07c051..000000000 --- a/src/com/android/photos/views/TiledImageView.java +++ /dev/null @@ -1,382 +0,0 @@ -/* - * 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.annotation.TargetApi; -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Matrix; -import android.graphics.Paint; -import android.graphics.Paint.Align; -import android.graphics.RectF; -import android.opengl.GLSurfaceView; -import android.opengl.GLSurfaceView.Renderer; -import android.os.Build; -import android.util.AttributeSet; -import android.view.Choreographer; -import android.view.Choreographer.FrameCallback; -import android.view.View; -import android.widget.FrameLayout; - -import com.android.gallery3d.glrenderer.BasicTexture; -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; - -/** - * Shows an image using {@link TiledImageRenderer} using either {@link GLSurfaceView} - * or {@link BlockingGLTextureView}. - */ -public class TiledImageView extends FrameLayout { - - private static final boolean USE_TEXTURE_VIEW = false; - private static final boolean IS_SUPPORTED = - Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; - private static final boolean USE_CHOREOGRAPHER = - Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; - - private BlockingGLTextureView mTextureView; - private GLSurfaceView mGLSurfaceView; - private boolean mInvalPending = false; - private FrameCallback mFrameCallback; - - private static class ImageRendererWrapper { - // Guarded by locks - float scale; - int centerX, centerY; - int rotation; - TileSource source; - Runnable isReadyCallback; - - // GL thread only - TiledImageRenderer image; - } - - private float[] mValues = new float[9]; - - // ------------------------- - // Guarded by mLock - // ------------------------- - private Object mLock = new Object(); - private ImageRendererWrapper mRenderer; - - public TiledImageView(Context context) { - this(context, null); - } - - public TiledImageView(Context context, AttributeSet attrs) { - super(context, attrs); - if (!IS_SUPPORTED) { - return; - } - - mRenderer = new ImageRendererWrapper(); - mRenderer.image = new TiledImageRenderer(this); - View view; - if (USE_TEXTURE_VIEW) { - mTextureView = new BlockingGLTextureView(context); - mTextureView.setRenderer(new TileRenderer()); - view = mTextureView; - } else { - mGLSurfaceView = new GLSurfaceView(context); - mGLSurfaceView.setEGLContextClientVersion(2); - mGLSurfaceView.setRenderer(new TileRenderer()); - mGLSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); - view = mGLSurfaceView; - } - addView(view, new LayoutParams( - LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); - //setTileSource(new ColoredTiles()); - } - - public void destroy() { - if (!IS_SUPPORTED) { - return; - } - if (USE_TEXTURE_VIEW) { - mTextureView.destroy(); - } else { - mGLSurfaceView.queueEvent(mFreeTextures); - } - } - - private Runnable mFreeTextures = new Runnable() { - - @Override - public void run() { - mRenderer.image.freeTextures(); - } - }; - - public void onPause() { - if (!IS_SUPPORTED) { - return; - } - if (!USE_TEXTURE_VIEW) { - mGLSurfaceView.onPause(); - } - } - - public void onResume() { - if (!IS_SUPPORTED) { - return; - } - if (!USE_TEXTURE_VIEW) { - mGLSurfaceView.onResume(); - } - } - - public void setTileSource(TileSource source, Runnable isReadyCallback) { - if (!IS_SUPPORTED) { - return; - } - synchronized (mLock) { - mRenderer.source = source; - mRenderer.isReadyCallback = isReadyCallback; - mRenderer.centerX = source != null ? source.getImageWidth() / 2 : 0; - mRenderer.centerY = source != null ? source.getImageHeight() / 2 : 0; - mRenderer.rotation = source != null ? source.getRotation() : 0; - mRenderer.scale = 0; - updateScaleIfNecessaryLocked(mRenderer); - } - invalidate(); - } - - @Override - protected void onLayout(boolean changed, int left, int top, int right, - int bottom) { - super.onLayout(changed, left, top, right, bottom); - if (!IS_SUPPORTED) { - return; - } - synchronized (mLock) { - updateScaleIfNecessaryLocked(mRenderer); - } - } - - private void updateScaleIfNecessaryLocked(ImageRendererWrapper renderer) { - if (renderer == null || renderer.source == null - || 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) { - if (!IS_SUPPORTED) { - return; - } - if (USE_TEXTURE_VIEW) { - mTextureView.render(); - } - super.dispatchDraw(canvas); - } - - @SuppressLint("NewApi") - @Override - public void setTranslationX(float translationX) { - if (!IS_SUPPORTED) { - return; - } - super.setTranslationX(translationX); - } - - @Override - public void invalidate() { - if (!IS_SUPPORTED) { - return; - } - if (USE_TEXTURE_VIEW) { - super.invalidate(); - mTextureView.invalidate(); - } else { - if (USE_CHOREOGRAPHER) { - invalOnVsync(); - } else { - mGLSurfaceView.requestRender(); - } - } - } - - @TargetApi(Build.VERSION_CODES.JELLY_BEAN) - private void invalOnVsync() { - if (!mInvalPending) { - mInvalPending = true; - if (mFrameCallback == null) { - mFrameCallback = new FrameCallback() { - @Override - public void doFrame(long frameTimeNanos) { - mInvalPending = false; - mGLSurfaceView.requestRender(); - } - }; - } - Choreographer.getInstance().postFrameCallback(mFrameCallback); - } - } - - private RectF mTempRectF = new RectF(); - public void positionFromMatrix(Matrix matrix) { - if (!IS_SUPPORTED) { - return; - } - if (mRenderer.source != null) { - final int rotation = mRenderer.source.getRotation(); - final boolean swap = !(rotation % 180 == 0); - final int width = swap ? mRenderer.source.getImageHeight() - : mRenderer.source.getImageWidth(); - final int height = swap ? mRenderer.source.getImageWidth() - : mRenderer.source.getImageHeight(); - mTempRectF.set(0, 0, width, height); - matrix.mapRect(mTempRectF); - matrix.getValues(mValues); - int cx = width / 2; - int cy = height / 2; - float scale = mValues[Matrix.MSCALE_X]; - int xoffset = Math.round((getWidth() - mTempRectF.width()) / 2 / scale); - int yoffset = Math.round((getHeight() - mTempRectF.height()) / 2 / scale); - if (rotation == 90 || rotation == 180) { - cx += (mTempRectF.left / scale) - xoffset; - } else { - cx -= (mTempRectF.left / scale) - xoffset; - } - if (rotation == 180 || rotation == 270) { - cy += (mTempRectF.top / scale) - yoffset; - } else { - cy -= (mTempRectF.top / scale) - yoffset; - } - mRenderer.scale = scale; - mRenderer.centerX = swap ? cy : cx; - mRenderer.centerY = swap ? cx : cy; - invalidate(); - } - } - - private class TileRenderer implements Renderer { - - private GLES20Canvas mCanvas; - - @Override - public void onSurfaceCreated(GL10 gl, EGLConfig config) { - mCanvas = new GLES20Canvas(); - BasicTexture.invalidateAllTextures(); - mRenderer.image.setModel(mRenderer.source, mRenderer.rotation); - } - - @Override - public void onSurfaceChanged(GL10 gl, int width, int height) { - mCanvas.setSize(width, height); - mRenderer.image.setViewSize(width, height); - } - - @Override - public void onDrawFrame(GL10 gl) { - mCanvas.clearBuffer(); - Runnable readyCallback; - synchronized (mLock) { - readyCallback = mRenderer.isReadyCallback; - mRenderer.image.setModel(mRenderer.source, mRenderer.rotation); - mRenderer.image.setPosition(mRenderer.centerX, mRenderer.centerY, - mRenderer.scale); - } - boolean complete = mRenderer.image.draw(mCanvas); - if (complete && readyCallback != null) { - synchronized (mLock) { - // Make sure we don't trample on a newly set callback/source - // if it changed while we were rendering - if (mRenderer.isReadyCallback == readyCallback) { - mRenderer.isReadyCallback = null; - } - } - if (readyCallback != null) { - post(readyCallback); - } - } - } - - } - - @SuppressWarnings("unused") - private static class ColoredTiles implements TileSource { - private static final 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 int getRotation() { - return 0; - } - - @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; - } - - @Override - public BasicTexture getPreview() { - return null; - } - } -} |