2 * Copyright (C) 2013 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.camera.widget;
19 import android.animation.Animator;
20 import android.animation.AnimatorSet;
21 import android.animation.TimeInterpolator;
22 import android.animation.ValueAnimator;
23 import android.annotation.TargetApi;
24 import android.app.Activity;
25 import android.content.Context;
26 import android.graphics.Canvas;
27 import android.graphics.Point;
28 import android.graphics.Rect;
29 import android.graphics.RectF;
30 import android.net.Uri;
31 import android.os.Build;
32 import android.os.Bundle;
33 import android.os.Handler;
34 import android.os.SystemClock;
35 import android.util.AttributeSet;
36 import android.util.DisplayMetrics;
37 import android.util.SparseArray;
38 import android.view.KeyEvent;
39 import android.view.MotionEvent;
40 import android.view.View;
41 import android.view.ViewGroup;
42 import android.view.accessibility.AccessibilityNodeInfo;
43 import android.view.animation.DecelerateInterpolator;
44 import android.widget.Scroller;
46 import com.android.camera.CameraActivity;
47 import com.android.camera.data.LocalData.ActionCallback;
48 import com.android.camera.debug.Log;
49 import com.android.camera.filmstrip.DataAdapter;
50 import com.android.camera.filmstrip.FilmstripController;
51 import com.android.camera.filmstrip.ImageData;
52 import com.android.camera.ui.FilmstripGestureRecognizer;
53 import com.android.camera.ui.ZoomView;
54 import com.android.camera.util.ApiHelper;
55 import com.android.camera.util.CameraUtil;
56 import com.android.camera2.R;
58 import java.lang.ref.WeakReference;
59 import java.util.ArrayDeque;
60 import java.util.Arrays;
61 import java.util.Queue;
63 public class FilmstripView extends ViewGroup {
65 * An action callback to be used for actions on the local media data items.
67 public static class ActionCallbackImpl implements ActionCallback {
68 private final WeakReference<Activity> mActivity;
71 * The given activity is used to start intents. It is wrapped in a weak
72 * reference to prevent leaks.
74 public ActionCallbackImpl(Activity activity) {
75 mActivity = new WeakReference<Activity>(activity);
79 * Fires an intent to play the video with the given URI and title.
82 public void playVideo(Uri uri, String title) {
83 Activity activity = mActivity.get();
84 if (activity != null) {
85 CameraUtil.playVideo(activity, uri, title);
91 private static final Log.Tag TAG = new Log.Tag("FilmstripView");
93 private static final int BUFFER_SIZE = 5;
94 private static final int GEOMETRY_ADJUST_TIME_MS = 400;
95 private static final int SNAP_IN_CENTER_TIME_MS = 600;
96 private static final float FLING_COASTING_DURATION_S = 0.05f;
97 private static final int ZOOM_ANIMATION_DURATION_MS = 200;
98 private static final int CAMERA_PREVIEW_SWIPE_THRESHOLD = 300;
99 private static final float FILM_STRIP_SCALE = 0.7f;
100 private static final float FULL_SCREEN_SCALE = 1f;
102 // The min velocity at which the user must have moved their finger in
103 // pixels per millisecond to count a vertical gesture as a promote/demote
104 // at short vertical distances.
105 private static final float PROMOTE_VELOCITY = 3.5f;
106 // The min distance relative to this view's height the user must have
107 // moved their finger to count a vertical gesture as a promote/demote if
108 // they moved their finger at least at PROMOTE_VELOCITY.
109 private static final float VELOCITY_PROMOTE_HEIGHT_RATIO = 1/10f;
110 // The min distance relative to this view's height the user must have
111 // moved their finger to count a vertical gesture as a promote/demote if
112 // they moved their finger at less than PROMOTE_VELOCITY.
113 private static final float PROMOTE_HEIGHT_RATIO = 1/2f;
115 private static final float TOLERANCE = 0.1f;
116 // Only check for intercepting touch events within first 500ms
117 private static final int SWIPE_TIME_OUT = 500;
118 private static final int DECELERATION_FACTOR = 4;
119 private static final float MOUSE_SCROLL_FACTOR = 128f;
121 private CameraActivity mActivity;
122 private ActionCallback mActionCallback;
123 private FilmstripGestureRecognizer mGestureRecognizer;
124 private FilmstripGestureRecognizer.Listener mGestureListener;
125 private DataAdapter mDataAdapter;
126 private int mViewGapInPixel;
127 private final Rect mDrawArea = new Rect();
129 private final int mCurrentItem = (BUFFER_SIZE - 1) / 2;
130 private float mScale;
131 private MyController mController;
132 private int mCenterX = -1;
133 private final ViewItem[] mViewItem = new ViewItem[BUFFER_SIZE];
135 private FilmstripController.FilmstripListener mListener;
136 private ZoomView mZoomView = null;
138 private MotionEvent mDown;
139 private boolean mCheckToIntercept = true;
141 private TimeInterpolator mViewAnimInterpolator;
143 // This is true if and only if the user is scrolling,
144 private boolean mIsUserScrolling;
145 private int mDataIdOnUserScrolling;
146 private float mOverScaleFactor = 1f;
148 private boolean mFullScreenUIHidden = false;
149 private final SparseArray<Queue<View>> recycledViews = new SparseArray<Queue<View>>();
152 * A helper class to tract and calculate the view coordination.
154 private class ViewItem {
156 /** The position of the left of the view in the whole filmstrip. */
157 private int mLeftPosition;
158 private final View mView;
159 private final ImageData mData;
160 private final RectF mViewArea;
161 private boolean mMaximumBitmapRequested;
163 private ValueAnimator mTranslationXAnimator;
164 private ValueAnimator mTranslationYAnimator;
165 private ValueAnimator mAlphaAnimator;
170 * @param id The id of the data from
171 * {@link com.android.camera.filmstrip.DataAdapter}.
172 * @param v The {@code View} representing the data.
174 public ViewItem(int id, View v, ImageData data) {
180 mMaximumBitmapRequested = false;
182 mViewArea = new RectF();
185 public boolean isMaximumBitmapRequested() {
186 return mMaximumBitmapRequested;
189 public void setMaximumBitmapRequested() {
190 mMaximumBitmapRequested = true;
194 * Returns the data id from
195 * {@link com.android.camera.filmstrip.DataAdapter}.
202 * Sets the data id from
203 * {@link com.android.camera.filmstrip.DataAdapter}.
205 public void setId(int id) {
209 /** Sets the left position of the view in the whole filmstrip. */
210 public void setLeftPosition(int pos) {
214 /** Returns the left position of the view in the whole filmstrip. */
215 public int getLeftPosition() {
216 return mLeftPosition;
219 /** Returns the translation of Y regarding the view scale. */
220 public float getTranslationY() {
221 return mView.getTranslationY() / mScale;
224 /** Returns the translation of X regarding the view scale. */
225 public float getTranslationX() {
226 return mView.getTranslationX() / mScale;
229 /** Sets the translation of Y regarding the view scale. */
230 public void setTranslationY(float transY) {
231 mView.setTranslationY(transY * mScale);
234 /** Sets the translation of X regarding the view scale. */
235 public void setTranslationX(float transX) {
236 mView.setTranslationX(transX * mScale);
239 /** Forwarding of {@link android.view.View#setAlpha(float)}. */
240 public void setAlpha(float alpha) {
241 mView.setAlpha(alpha);
244 /** Forwarding of {@link android.view.View#getAlpha()}. */
245 public float getAlpha() {
246 return mView.getAlpha();
249 /** Forwarding of {@link android.view.View#getMeasuredWidth()}. */
250 public int getMeasuredWidth() {
251 return mView.getMeasuredWidth();
255 * Animates the X translation of the view. Note: the animated value is
256 * not set directly by {@link android.view.View#setTranslationX(float)}
257 * because the value might be changed during in {@code onLayout()}.
258 * The animated value of X translation is specially handled in {@code
261 * @param targetX The final value.
262 * @param duration_ms The duration of the animation.
263 * @param interpolator Time interpolator.
265 public void animateTranslationX(
266 float targetX, long duration_ms, TimeInterpolator interpolator) {
267 if (mTranslationXAnimator == null) {
268 mTranslationXAnimator = new ValueAnimator();
269 mTranslationXAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
271 public void onAnimationUpdate(ValueAnimator valueAnimator) {
272 // We invalidate the filmstrip view instead of setting the
273 // translation X because the translation X of the view is
274 // touched in onLayout(). See the documentation of
275 // animateTranslationX().
280 runAnimation(mTranslationXAnimator, getTranslationX(), targetX, duration_ms,
285 * Animates the Y translation of the view.
287 * @param targetY The final value.
288 * @param duration_ms The duration of the animation.
289 * @param interpolator Time interpolator.
291 public void animateTranslationY(
292 float targetY, long duration_ms, TimeInterpolator interpolator) {
293 if (mTranslationYAnimator == null) {
294 mTranslationYAnimator = new ValueAnimator();
295 mTranslationYAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
297 public void onAnimationUpdate(ValueAnimator valueAnimator) {
298 setTranslationY((Float) valueAnimator.getAnimatedValue());
302 runAnimation(mTranslationYAnimator, getTranslationY(), targetY, duration_ms,
307 * Animates the alpha value of the view.
309 * @param targetAlpha The final value.
310 * @param duration_ms The duration of the animation.
311 * @param interpolator Time interpolator.
313 public void animateAlpha(float targetAlpha, long duration_ms,
314 TimeInterpolator interpolator) {
315 if (mAlphaAnimator == null) {
316 mAlphaAnimator = new ValueAnimator();
317 mAlphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
319 public void onAnimationUpdate(ValueAnimator valueAnimator) {
320 ViewItem.this.setAlpha((Float) valueAnimator.getAnimatedValue());
324 runAnimation(mAlphaAnimator, getAlpha(), targetAlpha, duration_ms, interpolator);
327 private void runAnimation(final ValueAnimator animator, final float startValue,
328 final float targetValue, final long duration_ms,
329 final TimeInterpolator interpolator) {
330 if (startValue == targetValue) {
333 animator.setInterpolator(interpolator);
334 animator.setDuration(duration_ms);
335 animator.setFloatValues(startValue, targetValue);
339 /** Adjusts the translation of X regarding the view scale. */
340 public void translateXScaledBy(float transX) {
341 setTranslationX(getTranslationX() + transX * mScale);
345 * Forwarding of {@link android.view.View#getHitRect(android.graphics.Rect)}.
347 public void getHitRect(Rect rect) {
348 mView.getHitRect(rect);
351 public int getCenterX() {
352 return mLeftPosition + mView.getMeasuredWidth() / 2;
355 /** Forwarding of {@link android.view.View#getVisibility()}. */
356 public int getVisibility() {
357 return mView.getVisibility();
360 /** Forwarding of {@link android.view.View#setVisibility(int)}. */
361 public void setVisibility(int visibility) {
362 mView.setVisibility(visibility);
366 * Notifies the {@link com.android.camera.filmstrip.DataAdapter} to
369 public void resizeView(Context context, int w, int h) {
370 mDataAdapter.resizeView(context, mDataId, mView, w, h);
374 * Adds the view of the data to the view hierarchy if necessary.
376 public void addViewToHierarchy() {
377 if (indexOfChild(mView) < 0) {
382 setVisibility(View.VISIBLE);
389 * Removes from the hierarchy. Keeps the view in the view hierarchy if
390 * view type is {@code VIEW_TYPE_STICKY} and set to invisible instead.
392 * @param force {@code true} to remove the view from the hierarchy
393 * regardless of the view type.
395 public void removeViewFromHierarchy(boolean force) {
396 if (force || mData.getViewType() != ImageData.VIEW_TYPE_STICKY) {
398 mData.recycle(mView);
399 recycleView(mView, mDataId);
401 setVisibility(View.INVISIBLE);
406 * Brings the view to front by
407 * {@link #bringChildToFront(android.view.View)}
409 public void bringViewToFront() {
410 bringChildToFront(mView);
414 * The visual x position of this view, in pixels.
416 public float getX() {
421 * The visual y position of this view, in pixels.
423 public float getY() {
428 * Forwarding of {@link android.view.View#measure(int, int)}.
430 public void measure(int widthSpec, int heightSpec) {
431 mView.measure(widthSpec, heightSpec);
434 private void layoutAt(int left, int top) {
435 mView.layout(left, top, left + mView.getMeasuredWidth(),
436 top + mView.getMeasuredHeight());
440 * The bounding rect of the view.
442 public RectF getViewRect() {
443 RectF r = new RectF();
444 r.left = mView.getX();
445 r.top = mView.getY();
446 r.right = r.left + mView.getWidth() * mView.getScaleX();
447 r.bottom = r.top + mView.getHeight() * mView.getScaleY();
451 private View getView() {
456 * Layouts the view in the area assuming the center of the area is at a
457 * specific point of the whole filmstrip.
459 * @param drawArea The area when filmstrip will show in.
460 * @param refCenter The absolute X coordination in the whole filmstrip
461 * of the center of {@code drawArea}.
462 * @param scale The scale of the view on the filmstrip.
464 public void layoutWithTranslationX(Rect drawArea, int refCenter, float scale) {
465 final float translationX =
466 ((mTranslationXAnimator != null && mTranslationXAnimator.isRunning()) ?
467 (Float) mTranslationXAnimator.getAnimatedValue() : 0);
469 (int) (drawArea.centerX() + (mLeftPosition - refCenter + translationX) * scale);
470 int top = (int) (drawArea.centerY() - (mView.getMeasuredHeight() / 2) * scale);
472 mView.setScaleX(scale);
473 mView.setScaleY(scale);
475 // update mViewArea for touch detection.
476 int l = mView.getLeft();
477 int t = mView.getTop();
479 l + mView.getMeasuredWidth() * scale,
480 t + mView.getMeasuredHeight() * scale);
483 /** Returns true if the point is in the view. */
484 public boolean areaContains(float x, float y) {
485 return mViewArea.contains(x, y);
489 * Return the width of the view.
491 public int getWidth() {
492 return mView.getWidth();
496 * Returns the position of the left edge of the view area content is drawn in.
498 public int getDrawAreaLeft() {
499 return Math.round(mViewArea.left);
502 public void copyAttributes(ViewItem item) {
503 setLeftPosition(item.getLeftPosition());
505 setTranslationX(item.getTranslationX());
506 if (item.mTranslationXAnimator != null) {
507 mTranslationXAnimator = item.mTranslationXAnimator;
508 mTranslationXAnimator.removeAllUpdateListeners();
509 mTranslationXAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
511 public void onAnimationUpdate(ValueAnimator valueAnimator) {
512 // We invalidate the filmstrip view instead of setting the
513 // translation X because the translation X of the view is
514 // touched in onLayout(). See the documentation of
515 // animateTranslationX().
521 setTranslationY(item.getTranslationY());
522 if (item.mTranslationYAnimator != null) {
523 mTranslationYAnimator = item.mTranslationYAnimator;
524 mTranslationYAnimator.removeAllUpdateListeners();
525 mTranslationYAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
527 public void onAnimationUpdate(ValueAnimator valueAnimator) {
528 setTranslationY((Float) valueAnimator.getAnimatedValue());
533 setAlpha(item.getAlpha());
534 if (item.mAlphaAnimator != null) {
535 mAlphaAnimator = item.mAlphaAnimator;
536 mAlphaAnimator.removeAllUpdateListeners();
537 mAlphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
539 public void onAnimationUpdate(ValueAnimator valueAnimator) {
540 ViewItem.this.setAlpha((Float) valueAnimator.getAnimatedValue());
547 * Apply a scale factor (i.e. {@code postScale}) on top of current scale at
548 * pivot point ({@code focusX}, {@code focusY}). Visually it should be the
549 * same as post concatenating current view's matrix with specified scale.
551 void postScale(float focusX, float focusY, float postScale, int viewportWidth,
552 int viewportHeight) {
553 float transX = mView.getTranslationX();
554 float transY = mView.getTranslationY();
555 // Pivot point is top left of the view, so we need to translate
556 // to scale around focus point
557 transX -= (focusX - getX()) * (postScale - 1f);
558 transY -= (focusY - getY()) * (postScale - 1f);
559 float scaleX = mView.getScaleX() * postScale;
560 float scaleY = mView.getScaleY() * postScale;
561 updateTransform(transX, transY, scaleX, scaleY, viewportWidth,
565 void updateTransform(float transX, float transY, float scaleX, float scaleY,
566 int viewportWidth, int viewportHeight) {
567 float left = transX + mView.getLeft();
568 float top = transY + mView.getTop();
569 RectF r = ZoomView.adjustToFitInBounds(new RectF(left, top,
570 left + mView.getWidth() * scaleX,
571 top + mView.getHeight() * scaleY),
572 viewportWidth, viewportHeight);
573 mView.setScaleX(scaleX);
574 mView.setScaleY(scaleY);
575 transX = r.left - mView.getLeft();
576 transY = r.top - mView.getTop();
577 mView.setTranslationX(transX);
578 mView.setTranslationY(transY);
581 void resetTransform() {
582 mView.setScaleX(FULL_SCREEN_SCALE);
583 mView.setScaleY(FULL_SCREEN_SCALE);
584 mView.setTranslationX(0f);
585 mView.setTranslationY(0f);
589 public String toString() {
590 return "DataID = " + mDataId + "\n\t left = " + mLeftPosition
591 + "\n\t viewArea = " + mViewArea
592 + "\n\t centerX = " + getCenterX()
593 + "\n\t view MeasuredSize = "
594 + mView.getMeasuredWidth() + ',' + mView.getMeasuredHeight()
595 + "\n\t view Size = " + mView.getWidth() + ',' + mView.getHeight()
596 + "\n\t view scale = " + mView.getScaleX();
601 public FilmstripView(Context context) {
603 init((CameraActivity) context);
607 public FilmstripView(Context context, AttributeSet attrs) {
608 super(context, attrs);
609 init((CameraActivity) context);
613 public FilmstripView(Context context, AttributeSet attrs, int defStyle) {
614 super(context, attrs, defStyle);
615 init((CameraActivity) context);
618 private void init(CameraActivity cameraActivity) {
619 setWillNotDraw(false);
620 mActivity = cameraActivity;
621 mActionCallback = new ActionCallbackImpl(mActivity);
623 mDataIdOnUserScrolling = 0;
624 mController = new MyController(cameraActivity);
625 mViewAnimInterpolator = new DecelerateInterpolator();
626 mZoomView = new ZoomView(cameraActivity);
627 mZoomView.setVisibility(GONE);
630 mGestureListener = new MyGestureReceiver();
632 new FilmstripGestureRecognizer(cameraActivity, mGestureListener);
633 mSlop = (int) getContext().getResources().getDimension(R.dimen.pie_touch_slop);
634 DisplayMetrics metrics = new DisplayMetrics();
635 mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
636 // Allow over scaling because on high density screens, pixels are too
637 // tiny to clearly see the details at 1:1 zoom. We should not scale
638 // beyond what 1:1 would look like on a medium density screen, as
639 // scaling beyond that would only yield blur.
640 mOverScaleFactor = (float) metrics.densityDpi / (float) DisplayMetrics.DENSITY_HIGH;
641 if (mOverScaleFactor < 1f) {
642 mOverScaleFactor = 1f;
645 setAccessibilityDelegate(new AccessibilityDelegate() {
647 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
648 super.onInitializeAccessibilityNodeInfo(host, info);
650 info.setClassName(FilmstripView.class.getName());
651 info.setScrollable(true);
652 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
653 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
657 public boolean performAccessibilityAction(View host, int action, Bundle args) {
658 if (!mController.isScrolling()) {
660 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
661 mController.goToNextItem();
664 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
665 boolean wentToPrevious = mController.goToPreviousItem();
666 if (!wentToPrevious) {
667 // at beginning of filmstrip, hide and go back to preview
668 mActivity.getCameraAppUI().hideFilmstrip();
672 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
673 // Prevent the view group itself from being selected.
674 // Instead, select the item in the center
675 final ViewItem currentItem = mViewItem[mCurrentItem];
676 currentItem.getView().performAccessibilityAction(action, args);
681 return super.performAccessibilityAction(host, action, args);
686 private void recycleView(View view, int dataId) {
687 final int viewType = (Integer) view.getTag(R.id.mediadata_tag_viewtype);
689 Queue<View> recycledViewsForType = recycledViews.get(viewType);
690 if (recycledViewsForType == null) {
691 recycledViewsForType = new ArrayDeque<View>();
692 recycledViews.put(viewType, recycledViewsForType);
694 recycledViewsForType.offer(view);
698 private View getRecycledView(int dataId) {
699 final int viewType = mDataAdapter.getItemViewType(dataId);
700 Queue<View> recycledViewsForType = recycledViews.get(viewType);
702 if (recycledViewsForType != null) {
703 result = recycledViewsForType.poll();
705 if (result != null) {
706 result.setVisibility(View.GONE);
712 * Returns the controller.
714 * @return The {@code Controller}.
716 public FilmstripController getController() {
721 * Returns the draw area width of the current item.
723 public int getCurrentItemLeft() {
724 return mViewItem[mCurrentItem].getDrawAreaLeft();
727 private void setListener(FilmstripController.FilmstripListener l) {
731 private void setViewGap(int viewGap) {
732 mViewGapInPixel = viewGap;
736 * Called after current item or zoom level has changed.
738 public void zoomAtIndexChanged() {
739 if (mViewItem[mCurrentItem] == null) {
742 int id = mViewItem[mCurrentItem].getId();
743 mListener.onZoomAtIndexChanged(id, mScale);
747 * Checks if the data is at the center.
749 * @param id The id of the data to check.
750 * @return {@code True} if the data is currently at the center.
752 private boolean isDataAtCenter(int id) {
753 if (mViewItem[mCurrentItem] == null) {
756 if (mViewItem[mCurrentItem].getId() == id
757 && isCurrentItemCentered()) {
763 private void measureViewItem(ViewItem item, int boundWidth, int boundHeight) {
764 int id = item.getId();
765 ImageData imageData = mDataAdapter.getImageData(id);
766 if (imageData == null) {
767 Log.e(TAG, "trying to measure a null item");
771 Point dim = CameraUtil.resizeToFill(imageData.getWidth(), imageData.getHeight(),
772 imageData.getRotation(), boundWidth, boundHeight);
774 item.measure(MeasureSpec.makeMeasureSpec(dim.x, MeasureSpec.EXACTLY),
775 MeasureSpec.makeMeasureSpec(dim.y, MeasureSpec.EXACTLY));
779 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
780 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
782 int boundWidth = MeasureSpec.getSize(widthMeasureSpec);
783 int boundHeight = MeasureSpec.getSize(heightMeasureSpec);
784 if (boundWidth == 0 || boundHeight == 0) {
785 // Either width or height is unknown, can't measure children yet.
789 for (ViewItem item : mViewItem) {
791 measureViewItem(item, boundWidth, boundHeight);
796 mZoomView.measure(MeasureSpec.makeMeasureSpec(widthMeasureSpec, MeasureSpec.EXACTLY),
797 MeasureSpec.makeMeasureSpec(heightMeasureSpec, MeasureSpec.EXACTLY));
800 private int findTheNearestView(int pointX) {
803 // Find the first non-null ViewItem.
804 while (nearest < BUFFER_SIZE
805 && (mViewItem[nearest] == null || mViewItem[nearest].getLeftPosition() == -1)) {
808 // No existing available ViewItem
809 if (nearest == BUFFER_SIZE) {
813 int min = Math.abs(pointX - mViewItem[nearest].getCenterX());
815 for (int itemID = nearest + 1; itemID < BUFFER_SIZE && mViewItem[itemID] != null; itemID++) {
817 if (mViewItem[itemID].getLeftPosition() == -1) {
821 int c = mViewItem[itemID].getCenterX();
822 int dist = Math.abs(pointX - c);
831 private ViewItem buildItemFromData(int dataID) {
832 if (mActivity.isDestroyed()) {
833 // Loading item data is call from multiple AsyncTasks and the
834 // activity may be finished when buildItemFromData is called.
835 Log.d(TAG, "Activity destroyed, don't load data");
838 ImageData data = mDataAdapter.getImageData(dataID);
843 // Always scale by fixed filmstrip scale, since we only show items when
844 // in filmstrip. Preloading images with a different scale and bounds
845 // interferes with caching.
846 int width = Math.round(FILM_STRIP_SCALE * getWidth());
847 int height = Math.round(FILM_STRIP_SCALE * getHeight());
848 Log.v(TAG, "suggesting item bounds: " + width + "x" + height);
849 mDataAdapter.suggestViewSizeBound(width, height);
852 View recycled = getRecycledView(dataID);
853 View v = mDataAdapter.getView(mActivity.getAndroidContext(), recycled, dataID,
858 ViewItem item = new ViewItem(dataID, v, data);
859 item.addViewToHierarchy();
863 private void checkItemAtMaxSize() {
864 ViewItem item = mViewItem[mCurrentItem];
865 if (item.isMaximumBitmapRequested()) {
868 item.setMaximumBitmapRequested();
869 // Request full size bitmap, or max that DataAdapter will create.
870 int id = item.getId();
871 int h = mDataAdapter.getImageData(id).getHeight();
872 int w = mDataAdapter.getImageData(id).getWidth();
873 item.resizeView(mActivity, w, h);
876 private void removeItem(int itemID) {
877 if (itemID >= mViewItem.length || mViewItem[itemID] == null) {
880 ImageData data = mDataAdapter.getImageData(mViewItem[itemID].getId());
882 Log.e(TAG, "trying to remove a null item");
885 mViewItem[itemID].removeViewFromHierarchy(false);
886 mViewItem[itemID] = null;
890 * We try to keep the one closest to the center of the screen at position
893 private void stepIfNeeded() {
894 if (!inFilmstrip() && !inFullScreen()) {
895 // The good timing to step to the next view is when everything is
896 // not in transition.
899 final int nearest = findTheNearestView(mCenterX);
901 if (nearest == -1 || nearest == mCurrentItem) {
904 int prevDataId = (mViewItem[mCurrentItem] == null ? -1 : mViewItem[mCurrentItem].getId());
905 final int adjust = nearest - mCurrentItem;
907 for (int k = 0; k < adjust; k++) {
910 for (int k = 0; k + adjust < BUFFER_SIZE; k++) {
911 mViewItem[k] = mViewItem[k + adjust];
913 for (int k = BUFFER_SIZE - adjust; k < BUFFER_SIZE; k++) {
915 if (mViewItem[k - 1] != null) {
916 mViewItem[k] = buildItemFromData(mViewItem[k - 1].getId() + 1);
921 for (int k = BUFFER_SIZE - 1; k >= BUFFER_SIZE + adjust; k--) {
924 for (int k = BUFFER_SIZE - 1; k + adjust >= 0; k--) {
925 mViewItem[k] = mViewItem[k + adjust];
927 for (int k = -1 - adjust; k >= 0; k--) {
929 if (mViewItem[k + 1] != null) {
930 mViewItem[k] = buildItemFromData(mViewItem[k + 1].getId() - 1);
935 if (mListener != null) {
936 mListener.onDataFocusChanged(prevDataId, mViewItem[mCurrentItem].getId());
937 final int firstVisible = mViewItem[mCurrentItem].getId() - 2;
938 final int visibleItemCount = firstVisible + BUFFER_SIZE;
939 final int totalItemCount = mDataAdapter.getTotalNumber();
940 mListener.onScroll(firstVisible, visibleItemCount, totalItemCount);
942 zoomAtIndexChanged();
946 * Check the bounds of {@code mCenterX}. Always call this function after: 1.
947 * Any changes to {@code mCenterX}. 2. Any size change of the view items.
949 * @return Whether clamp happened.
951 private boolean clampCenterX() {
952 ViewItem curr = mViewItem[mCurrentItem];
957 boolean stopScroll = false;
958 if (curr.getId() == 1 && mCenterX < curr.getCenterX() && mDataIdOnUserScrolling > 1 &&
959 mDataAdapter.getImageData(0).getViewType() == ImageData.VIEW_TYPE_STICKY &&
960 mController.isScrolling()) {
963 if (curr.getId() == 0 && mCenterX < curr.getCenterX()) {
964 // Stop at the first ViewItem.
968 if (curr.getId() == mDataAdapter.getTotalNumber() - 1
969 && mCenterX > curr.getCenterX()) {
975 mCenterX = curr.getCenterX();
982 * Reorders the child views to be consistent with their data ID. This method
983 * should be called after adding/removing views.
985 private void adjustChildZOrder() {
986 for (int i = BUFFER_SIZE - 1; i >= 0; i--) {
987 if (mViewItem[i] == null) {
990 mViewItem[i].bringViewToFront();
992 // ZoomView is a special case to always be in the front. In L set to
993 // max elevation to make sure ZoomView is above other elevated views.
994 bringChildToFront(mZoomView);
995 if (ApiHelper.isLOrHigher()) {
996 setMaxElevation(mZoomView);
1000 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
1001 private void setMaxElevation(View v) {
1002 v.setElevation(Float.MAX_VALUE);
1006 * Returns the ID of the current item, or -1 if there is no data.
1008 private int getCurrentId() {
1009 ViewItem current = mViewItem[mCurrentItem];
1010 if (current == null) {
1013 return current.getId();
1017 * Keep the current item in the center. This functions does not check if the
1018 * current item is null.
1020 private void snapInCenter() {
1021 final ViewItem currItem = mViewItem[mCurrentItem];
1022 if (currItem == null) {
1025 final int currentViewCenter = currItem.getCenterX();
1026 if (mController.isScrolling() || mIsUserScrolling
1027 || isCurrentItemCentered()) {
1031 int snapInTime = (int) (SNAP_IN_CENTER_TIME_MS
1032 * ((float) Math.abs(mCenterX - currentViewCenter))
1033 / mDrawArea.width());
1034 mController.scrollToPosition(currentViewCenter,
1036 if (isViewTypeSticky(currItem) && !mController.isScaling() && mScale != FULL_SCREEN_SCALE) {
1037 // Now going to full screen camera
1038 mController.goToFullScreen();
1043 * Translates the {@link ViewItem} on the left of the current one to match
1044 * the full-screen layout. In full-screen, we show only one {@link ViewItem}
1045 * which occupies the whole screen. The other left ones are put on the left
1046 * side in full scales. Does nothing if there's no next item.
1048 * @param currItem The item ID of the current one to be translated.
1049 * @param drawAreaWidth The width of the current draw area.
1050 * @param scaleFraction A {@code float} between 0 and 1. 0 if the current
1051 * scale is {@code FILM_STRIP_SCALE}. 1 if the current scale is
1052 * {@code FULL_SCREEN_SCALE}.
1054 private void translateLeftViewItem(
1055 int currItem, int drawAreaWidth, float scaleFraction) {
1056 if (currItem < 0 || currItem > BUFFER_SIZE - 1) {
1057 Log.e(TAG, "currItem id out of bound.");
1061 final ViewItem curr = mViewItem[currItem];
1062 final ViewItem next = mViewItem[currItem + 1];
1063 if (curr == null || next == null) {
1064 Log.e(TAG, "Invalid view item (curr or next == null). curr = "
1069 final int currCenterX = curr.getCenterX();
1070 final int nextCenterX = next.getCenterX();
1071 final int translate = (int) ((nextCenterX - drawAreaWidth
1072 - currCenterX) * scaleFraction);
1074 curr.layoutWithTranslationX(mDrawArea, mCenterX, mScale);
1076 curr.setVisibility(VISIBLE);
1078 if (inFullScreen()) {
1079 curr.setTranslationX(translate * (mCenterX - currCenterX) / (nextCenterX - currCenterX));
1081 curr.setTranslationX(translate);
1086 * Fade out the {@link ViewItem} on the right of the current one in
1087 * full-screen layout. Does nothing if there's no previous item.
1089 * @param currItemId The ID of the item to fade.
1091 private void fadeAndScaleRightViewItem(int currItemId) {
1092 if (currItemId < 1 || currItemId > BUFFER_SIZE) {
1093 Log.e(TAG, "currItem id out of bound.");
1097 final ViewItem currItem = mViewItem[currItemId];
1098 final ViewItem prevItem = mViewItem[currItemId - 1];
1099 if (currItem == null || prevItem == null) {
1100 Log.e(TAG, "Invalid view item (curr or prev == null). curr = "
1105 if (currItemId > mCurrentItem + 1) {
1106 // Every item not right next to the mCurrentItem is invisible.
1107 currItem.setVisibility(INVISIBLE);
1110 final int prevCenterX = prevItem.getCenterX();
1111 if (mCenterX <= prevCenterX) {
1112 // Shortcut. If the position is at the center of the previous one,
1113 // set to invisible too.
1114 currItem.setVisibility(INVISIBLE);
1117 final int currCenterX = currItem.getCenterX();
1118 final float fadeDownFraction =
1119 ((float) mCenterX - prevCenterX) / (currCenterX - prevCenterX);
1120 currItem.layoutWithTranslationX(mDrawArea, currCenterX,
1121 FILM_STRIP_SCALE + (1f - FILM_STRIP_SCALE) * fadeDownFraction);
1122 currItem.setAlpha(fadeDownFraction);
1123 currItem.setTranslationX(0);
1124 currItem.setVisibility(VISIBLE);
1127 private void layoutViewItems(boolean layoutChanged) {
1128 if (mViewItem[mCurrentItem] == null ||
1129 mDrawArea.width() == 0 ||
1130 mDrawArea.height() == 0) {
1134 // If the layout changed, we need to adjust the current position so
1135 // that if an item is centered before the change, it's still centered.
1136 if (layoutChanged) {
1137 mViewItem[mCurrentItem].setLeftPosition(
1138 mCenterX - mViewItem[mCurrentItem].getMeasuredWidth() / 2);
1145 * Transformed scale fraction between 0 and 1. 0 if the scale is
1146 * {@link FILM_STRIP_SCALE}. 1 if the scale is {@link FULL_SCREEN_SCALE}
1149 final float scaleFraction = mViewAnimInterpolator.getInterpolation(
1150 (mScale - FILM_STRIP_SCALE) / (FULL_SCREEN_SCALE - FILM_STRIP_SCALE));
1151 final int fullScreenWidth = mDrawArea.width() + mViewGapInPixel;
1153 // Decide the position for all view items on the left and the right
1157 for (int itemID = mCurrentItem - 1; itemID >= 0; itemID--) {
1158 final ViewItem curr = mViewItem[itemID];
1163 // First, layout relatively to the next one.
1164 final int currLeft = mViewItem[itemID + 1].getLeftPosition()
1165 - curr.getMeasuredWidth() - mViewGapInPixel;
1166 curr.setLeftPosition(currLeft);
1169 for (int itemID = mCurrentItem + 1; itemID < BUFFER_SIZE; itemID++) {
1170 final ViewItem curr = mViewItem[itemID];
1175 // First, layout relatively to the previous one.
1176 final ViewItem prev = mViewItem[itemID - 1];
1177 final int currLeft =
1178 prev.getLeftPosition() + prev.getMeasuredWidth()
1180 curr.setLeftPosition(currLeft);
1183 // Special case for the one immediately on the right of the camera
1185 boolean immediateRight =
1186 (mViewItem[mCurrentItem].getId() == 1 &&
1187 mDataAdapter.getImageData(0).getViewType() == ImageData.VIEW_TYPE_STICKY);
1189 // Layout the current ViewItem first.
1190 if (immediateRight) {
1191 // Just do a simple layout without any special translation or
1192 // fading. The implementation in Gallery does not push the first
1193 // photo to the bottom of the camera preview. Simply place the
1194 // photo on the right of the preview.
1195 final ViewItem currItem = mViewItem[mCurrentItem];
1196 currItem.layoutWithTranslationX(mDrawArea, mCenterX, mScale);
1197 currItem.setTranslationX(0f);
1198 currItem.setAlpha(1f);
1199 } else if (scaleFraction == 1f) {
1200 final ViewItem currItem = mViewItem[mCurrentItem];
1201 final int currCenterX = currItem.getCenterX();
1202 if (mCenterX < currCenterX) {
1203 // In full-screen and mCenterX is on the left of the center,
1204 // we draw the current one to "fade down".
1205 fadeAndScaleRightViewItem(mCurrentItem);
1206 } else if (mCenterX > currCenterX) {
1207 // In full-screen and mCenterX is on the right of the center,
1208 // we draw the current one translated.
1209 translateLeftViewItem(mCurrentItem, fullScreenWidth, scaleFraction);
1211 currItem.layoutWithTranslationX(mDrawArea, mCenterX, mScale);
1212 currItem.setTranslationX(0f);
1213 currItem.setAlpha(1f);
1216 final ViewItem currItem = mViewItem[mCurrentItem];
1217 // The normal filmstrip has no translation for the current item. If
1218 // it has translation before, gradually set it to zero.
1219 currItem.setTranslationX(currItem.getTranslationX() * scaleFraction);
1220 currItem.layoutWithTranslationX(mDrawArea, mCenterX, mScale);
1221 if (mViewItem[mCurrentItem - 1] == null) {
1222 currItem.setAlpha(1f);
1224 final int currCenterX = currItem.getCenterX();
1225 final int prevCenterX = mViewItem[mCurrentItem - 1].getCenterX();
1226 final float fadeDownFraction =
1227 ((float) mCenterX - prevCenterX) / (currCenterX - prevCenterX);
1229 (1 - fadeDownFraction) * (1 - scaleFraction) + fadeDownFraction);
1233 // Layout the rest dependent on the current scale.
1235 // Items on the left
1236 for (int itemID = mCurrentItem - 1; itemID >= 0; itemID--) {
1237 final ViewItem curr = mViewItem[itemID];
1241 translateLeftViewItem(itemID, fullScreenWidth, scaleFraction);
1244 // Items on the right
1245 for (int itemID = mCurrentItem + 1; itemID < BUFFER_SIZE; itemID++) {
1246 final ViewItem curr = mViewItem[itemID];
1251 curr.layoutWithTranslationX(mDrawArea, mCenterX, mScale);
1252 if (curr.getId() == 1 && isViewTypeSticky(curr)) {
1253 // Special case for the one next to the camera preview.
1258 if (scaleFraction == 1) {
1259 // It's in full-screen mode.
1260 fadeAndScaleRightViewItem(itemID);
1262 boolean setToVisible = (curr.getVisibility() == INVISIBLE);
1264 if (itemID == mCurrentItem + 1) {
1265 curr.setAlpha(1f - scaleFraction);
1267 if (scaleFraction == 0f) {
1270 setToVisible = false;
1275 curr.setVisibility(VISIBLE);
1278 curr.setTranslationX(
1279 (mViewItem[mCurrentItem].getLeftPosition() - curr.getLeftPosition()) *
1287 private boolean isViewTypeSticky(ViewItem item) {
1291 return mDataAdapter.getImageData(item.getId()).getViewType() ==
1292 ImageData.VIEW_TYPE_STICKY;
1296 public void onDraw(Canvas c) {
1297 // TODO: remove layoutViewItems() here.
1298 layoutViewItems(false);
1303 protected void onLayout(boolean changed, int l, int t, int r, int b) {
1306 mDrawArea.right = r - l;
1307 mDrawArea.bottom = b - t;
1308 mZoomView.layout(mDrawArea.left, mDrawArea.top, mDrawArea.right, mDrawArea.bottom);
1309 // TODO: Need a more robust solution to decide when to re-layout
1310 // If in the middle of zooming, only re-layout when the layout has
1312 if (!inZoomView() || changed) {
1314 layoutViewItems(changed);
1319 * Clears the translation and scale that has been set on the view, cancels
1320 * any loading request for image partial decoding, and hides zoom view. This
1321 * is needed for when there is a layout change (e.g. when users re-enter the
1322 * app, or rotate the device, etc).
1324 private void resetZoomView() {
1325 if (!inZoomView()) {
1328 ViewItem current = mViewItem[mCurrentItem];
1329 if (current == null) {
1332 mScale = FULL_SCREEN_SCALE;
1333 mController.cancelZoomAnimation();
1334 mController.cancelFlingAnimation();
1335 current.resetTransform();
1336 mController.cancelLoadingZoomedImage();
1337 mZoomView.setVisibility(GONE);
1338 mController.setSurroundingViewsVisible(true);
1341 private void hideZoomView() {
1343 mController.cancelLoadingZoomedImage();
1344 mZoomView.setVisibility(GONE);
1348 private void slideViewBack(ViewItem item) {
1349 item.animateTranslationX(0, GEOMETRY_ADJUST_TIME_MS, mViewAnimInterpolator);
1350 item.animateTranslationY(0, GEOMETRY_ADJUST_TIME_MS, mViewAnimInterpolator);
1351 item.animateAlpha(1f, GEOMETRY_ADJUST_TIME_MS, mViewAnimInterpolator);
1354 private void animateItemRemoval(int dataID, final ImageData data) {
1355 if (mScale > FULL_SCREEN_SCALE) {
1358 int removedItemId = findItemByDataID(dataID);
1360 // adjust the data id to be consistent
1361 for (int i = 0; i < BUFFER_SIZE; i++) {
1362 if (mViewItem[i] == null || mViewItem[i].getId() <= dataID) {
1365 mViewItem[i].setId(mViewItem[i].getId() - 1);
1367 if (removedItemId == -1) {
1371 final ViewItem removedItem = mViewItem[removedItemId];
1372 final int offsetX = removedItem.getMeasuredWidth() + mViewGapInPixel;
1374 for (int i = removedItemId + 1; i < BUFFER_SIZE; i++) {
1375 if (mViewItem[i] != null) {
1376 mViewItem[i].setLeftPosition(mViewItem[i].getLeftPosition() - offsetX);
1380 if (removedItemId >= mCurrentItem
1381 && mViewItem[removedItemId].getId() < mDataAdapter.getTotalNumber()) {
1382 // Fill the removed item by left shift when the current one or
1383 // anyone on the right is removed, and there's more data on the
1385 for (int i = removedItemId; i < BUFFER_SIZE - 1; i++) {
1386 mViewItem[i] = mViewItem[i + 1];
1389 // pull data out from the DataAdapter for the last one.
1390 int curr = BUFFER_SIZE - 1;
1391 int prev = curr - 1;
1392 if (mViewItem[prev] != null) {
1393 mViewItem[curr] = buildItemFromData(mViewItem[prev].getId() + 1);
1396 // The animation part.
1397 if (inFullScreen()) {
1398 mViewItem[mCurrentItem].setVisibility(VISIBLE);
1399 ViewItem nextItem = mViewItem[mCurrentItem + 1];
1400 if (nextItem != null) {
1401 nextItem.setVisibility(INVISIBLE);
1405 // Translate the views to their original places.
1406 for (int i = removedItemId; i < BUFFER_SIZE; i++) {
1407 if (mViewItem[i] != null) {
1408 mViewItem[i].setTranslationX(offsetX);
1412 // The end of the filmstrip might have been changed.
1413 // The mCenterX might be out of the bound.
1414 ViewItem currItem = mViewItem[mCurrentItem];
1415 if(currItem!=null) {
1416 if (currItem.getId() == mDataAdapter.getTotalNumber() - 1
1417 && mCenterX > currItem.getCenterX()) {
1418 int adjustDiff = currItem.getCenterX() - mCenterX;
1419 mCenterX = currItem.getCenterX();
1420 for (int i = 0; i < BUFFER_SIZE; i++) {
1421 if (mViewItem[i] != null) {
1422 mViewItem[i].translateXScaledBy(adjustDiff);
1427 // CurrItem should NOT be NULL, but if is, at least don't crash.
1428 Log.w(TAG,"Caught invalid update in removal animation.");
1431 // fill the removed place by right shift
1432 mCenterX -= offsetX;
1434 for (int i = removedItemId; i > 0; i--) {
1435 mViewItem[i] = mViewItem[i - 1];
1438 // pull data out from the DataAdapter for the first one.
1440 int next = curr + 1;
1441 if (mViewItem[next] != null) {
1442 mViewItem[curr] = buildItemFromData(mViewItem[next].getId() - 1);
1445 // Translate the views to their original places.
1446 for (int i = removedItemId; i >= 0; i--) {
1447 if (mViewItem[i] != null) {
1448 mViewItem[i].setTranslationX(-offsetX);
1453 int transY = getHeight() / 8;
1454 if (removedItem.getTranslationY() < 0) {
1457 removedItem.animateTranslationY(removedItem.getTranslationY() + transY,
1458 GEOMETRY_ADJUST_TIME_MS, mViewAnimInterpolator);
1459 removedItem.animateAlpha(0f, GEOMETRY_ADJUST_TIME_MS, mViewAnimInterpolator);
1460 postDelayed(new Runnable() {
1463 removedItem.removeViewFromHierarchy(false);
1465 }, GEOMETRY_ADJUST_TIME_MS);
1467 adjustChildZOrder();
1470 // Now, slide every one back.
1471 if (mViewItem[mCurrentItem] == null) {
1474 for (int i = 0; i < BUFFER_SIZE; i++) {
1475 if (mViewItem[i] != null
1476 && mViewItem[i].getTranslationX() != 0f) {
1477 slideViewBack(mViewItem[i]);
1480 if (isCurrentItemCentered() && isViewTypeSticky(mViewItem[mCurrentItem])) {
1481 // Special case for scrolling onto the camera preview after removal.
1482 mController.goToFullScreen();
1486 // returns -1 on failure.
1487 private int findItemByDataID(int dataID) {
1488 for (int i = 0; i < BUFFER_SIZE; i++) {
1489 if (mViewItem[i] != null
1490 && mViewItem[i].getId() == dataID) {
1497 private void updateInsertion(int dataID) {
1498 int insertedItemId = findItemByDataID(dataID);
1499 if (insertedItemId == -1) {
1500 // Not in the current item buffers. Check if it's inserted
1502 if (dataID == mDataAdapter.getTotalNumber() - 1) {
1503 int prev = findItemByDataID(dataID - 1);
1504 if (prev >= 0 && prev < BUFFER_SIZE - 1) {
1505 // The previous data is in the buffer and we still
1506 // have room for the inserted data.
1507 insertedItemId = prev + 1;
1512 // adjust the data id to be consistent
1513 for (int i = 0; i < BUFFER_SIZE; i++) {
1514 if (mViewItem[i] == null || mViewItem[i].getId() < dataID) {
1517 mViewItem[i].setId(mViewItem[i].getId() + 1);
1519 if (insertedItemId == -1) {
1523 final ImageData data = mDataAdapter.getImageData(dataID);
1524 Point dim = CameraUtil
1525 .resizeToFill(data.getWidth(), data.getHeight(), data.getRotation(),
1526 getMeasuredWidth(), getMeasuredHeight());
1527 final int offsetX = dim.x + mViewGapInPixel;
1528 ViewItem viewItem = buildItemFromData(dataID);
1529 if (viewItem == null) {
1530 Log.w(TAG, "unable to build inserted item from data");
1534 if (insertedItemId >= mCurrentItem) {
1535 if (insertedItemId == mCurrentItem) {
1536 viewItem.setLeftPosition(mViewItem[mCurrentItem].getLeftPosition());
1538 // Shift right to make rooms for newly inserted item.
1539 removeItem(BUFFER_SIZE - 1);
1540 for (int i = BUFFER_SIZE - 1; i > insertedItemId; i--) {
1541 mViewItem[i] = mViewItem[i - 1];
1542 if (mViewItem[i] != null) {
1543 mViewItem[i].setTranslationX(-offsetX);
1544 slideViewBack(mViewItem[i]);
1548 // Shift left. Put the inserted data on the left instead of the
1551 if (insertedItemId < 0) {
1555 for (int i = 1; i <= insertedItemId; i++) {
1556 if (mViewItem[i] != null) {
1557 mViewItem[i].setTranslationX(offsetX);
1558 slideViewBack(mViewItem[i]);
1559 mViewItem[i - 1] = mViewItem[i];
1564 mViewItem[insertedItemId] = viewItem;
1565 viewItem.setAlpha(0f);
1566 viewItem.setTranslationY(getHeight() / 8);
1567 slideViewBack(viewItem);
1568 adjustChildZOrder();
1572 private void setDataAdapter(DataAdapter adapter) {
1573 mDataAdapter = adapter;
1574 int maxEdge = (int) (Math.max(this.getHeight(), this.getWidth())
1575 * FILM_STRIP_SCALE);
1576 mDataAdapter.suggestViewSizeBound(maxEdge, maxEdge);
1577 mDataAdapter.setListener(new DataAdapter.Listener() {
1579 public void onDataLoaded() {
1584 public void onDataUpdated(DataAdapter.UpdateReporter reporter) {
1589 public void onDataInserted(int dataId, ImageData data) {
1590 if (mViewItem[mCurrentItem] == null) {
1591 // empty now, simply do a reload.
1594 updateInsertion(dataId);
1596 if (mListener != null) {
1597 mListener.onDataFocusChanged(dataId, getCurrentId());
1602 public void onDataRemoved(int dataId, ImageData data) {
1603 animateItemRemoval(dataId, data);
1604 if (mListener != null) {
1605 mListener.onDataFocusChanged(dataId, getCurrentId());
1611 private boolean inFilmstrip() {
1612 return (mScale == FILM_STRIP_SCALE);
1615 private boolean inFullScreen() {
1616 return (mScale == FULL_SCREEN_SCALE);
1619 private boolean inZoomView() {
1620 return (mScale > FULL_SCREEN_SCALE);
1623 private boolean isCameraPreview() {
1624 return isViewTypeSticky(mViewItem[mCurrentItem]);
1627 private boolean inCameraFullscreen() {
1628 return isDataAtCenter(0) && inFullScreen()
1629 && (isViewTypeSticky(mViewItem[mCurrentItem]));
1633 public boolean onInterceptTouchEvent(MotionEvent ev) {
1634 if (mController.isScrolling()) {
1638 if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
1639 mCheckToIntercept = true;
1640 mDown = MotionEvent.obtain(ev);
1641 ViewItem viewItem = mViewItem[mCurrentItem];
1642 // Do not intercept touch if swipe is not enabled
1643 if (viewItem != null && !mDataAdapter.canSwipeInFullScreen(viewItem.getId())) {
1644 mCheckToIntercept = false;
1647 } else if (ev.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN) {
1648 // Do not intercept touch once child is in zoom mode
1649 mCheckToIntercept = false;
1652 if (!mCheckToIntercept) {
1655 if (ev.getEventTime() - ev.getDownTime() > SWIPE_TIME_OUT) {
1658 int deltaX = (int) (ev.getX() - mDown.getX());
1659 int deltaY = (int) (ev.getY() - mDown.getY());
1660 if (ev.getActionMasked() == MotionEvent.ACTION_MOVE
1661 && deltaX < mSlop * (-1)) {
1662 // intercept left swipe
1663 if (Math.abs(deltaX) >= Math.abs(deltaY) * 2) {
1672 public boolean onTouchEvent(MotionEvent ev) {
1673 return mGestureRecognizer.onTouchEvent(ev);
1677 public boolean onGenericMotionEvent(MotionEvent ev) {
1678 mGestureRecognizer.onGenericMotionEvent(ev);
1682 FilmstripGestureRecognizer.Listener getGestureListener() {
1683 return mGestureListener;
1686 private void updateViewItem(int itemID) {
1687 ViewItem item = mViewItem[itemID];
1689 Log.e(TAG, "trying to update an null item");
1692 item.removeViewFromHierarchy(true);
1694 ViewItem newItem = buildItemFromData(item.getId());
1695 if (newItem == null) {
1696 Log.e(TAG, "new item is null");
1697 // keep using the old data.
1698 item.addViewToHierarchy();
1701 newItem.copyAttributes(item);
1702 mViewItem[itemID] = newItem;
1703 mZoomView.resetDecoder();
1705 boolean stopScroll = clampCenterX();
1707 mController.stopScrolling(true);
1709 adjustChildZOrder();
1711 if (mListener != null) {
1712 mListener.onDataUpdated(newItem.getId());
1716 /** Some of the data is changed. */
1717 private void update(DataAdapter.UpdateReporter reporter) {
1719 if (mViewItem[mCurrentItem] == null) {
1724 // Check the current one.
1725 ViewItem curr = mViewItem[mCurrentItem];
1726 int dataId = curr.getId();
1727 if (reporter.isDataRemoved(dataId)) {
1731 if (reporter.isDataUpdated(dataId)) {
1732 updateViewItem(mCurrentItem);
1733 final ImageData data = mDataAdapter.getImageData(dataId);
1734 if (!mIsUserScrolling && !mController.isScrolling()) {
1735 // If there is no scrolling at all, adjust mCenterX to place
1736 // the current item at the center.
1737 Point dim = CameraUtil.resizeToFill(data.getWidth(), data.getHeight(),
1738 data.getRotation(), getMeasuredWidth(), getMeasuredHeight());
1739 mCenterX = curr.getLeftPosition() + dim.x / 2;
1744 for (int i = mCurrentItem - 1; i >= 0; i--) {
1745 curr = mViewItem[i];
1747 dataId = curr.getId();
1748 if (reporter.isDataRemoved(dataId) || reporter.isDataUpdated(dataId)) {
1752 ViewItem next = mViewItem[i + 1];
1754 mViewItem[i] = buildItemFromData(next.getId() - 1);
1760 for (int i = mCurrentItem + 1; i < BUFFER_SIZE; i++) {
1761 curr = mViewItem[i];
1763 dataId = curr.getId();
1764 if (reporter.isDataRemoved(dataId) || reporter.isDataUpdated(dataId)) {
1768 ViewItem prev = mViewItem[i - 1];
1770 mViewItem[i] = buildItemFromData(prev.getId() + 1);
1774 adjustChildZOrder();
1775 // Request a layout to find the measured width/height of the view first.
1777 // Update photo sphere visibility after metadata fully written.
1781 * The whole data might be totally different. Flush all and load from the
1782 * start. Filmstrip will be centered on the first item, i.e. the camera
1785 private void reload() {
1786 mController.stopScrolling(true);
1787 mController.stopScale();
1788 mDataIdOnUserScrolling = 0;
1791 if (mViewItem[mCurrentItem] != null) {
1792 prevId = mViewItem[mCurrentItem].getId();
1795 // Remove all views from the mViewItem buffer, except the camera view.
1796 for (int i = 0; i < mViewItem.length; i++) {
1797 if (mViewItem[i] == null) {
1800 mViewItem[i].removeViewFromHierarchy(false);
1803 // Clear out the mViewItems and rebuild with camera in the center.
1804 Arrays.fill(mViewItem, null);
1805 int dataNumber = mDataAdapter.getTotalNumber();
1806 if (dataNumber == 0) {
1810 mViewItem[mCurrentItem] = buildItemFromData(0);
1811 if (mViewItem[mCurrentItem] == null) {
1814 mViewItem[mCurrentItem].setLeftPosition(0);
1815 for (int i = mCurrentItem + 1; i < BUFFER_SIZE; i++) {
1816 mViewItem[i] = buildItemFromData(mViewItem[i - 1].getId() + 1);
1817 if (mViewItem[i] == null) {
1822 // Ensure that the views in mViewItem will layout the first in the
1823 // center of the display upon a reload.
1825 mScale = FILM_STRIP_SCALE;
1827 adjustChildZOrder();
1830 if (mListener != null) {
1831 mListener.onDataReloaded();
1832 mListener.onDataFocusChanged(prevId, mViewItem[mCurrentItem].getId());
1836 private void promoteData(int itemID, int dataID) {
1837 if (mListener != null) {
1838 mListener.onFocusedDataPromoted(dataID);
1842 private void demoteData(int itemID, int dataID) {
1843 if (mListener != null) {
1844 mListener.onFocusedDataDemoted(dataID);
1848 private void onEnterFilmstrip() {
1849 if (mListener != null) {
1850 mListener.onEnterFilmstrip(getCurrentId());
1854 private void onLeaveFilmstrip() {
1855 if (mListener != null) {
1856 mListener.onLeaveFilmstrip(getCurrentId());
1860 private void onEnterFullScreen() {
1861 mFullScreenUIHidden = false;
1862 if (mListener != null) {
1863 mListener.onEnterFullScreenUiShown(getCurrentId());
1867 private void onLeaveFullScreen() {
1868 if (mListener != null) {
1869 mListener.onLeaveFullScreenUiShown(getCurrentId());
1873 private void onEnterFullScreenUiHidden() {
1874 mFullScreenUIHidden = true;
1875 if (mListener != null) {
1876 mListener.onEnterFullScreenUiHidden(getCurrentId());
1880 private void onLeaveFullScreenUiHidden() {
1881 mFullScreenUIHidden = false;
1882 if (mListener != null) {
1883 mListener.onLeaveFullScreenUiHidden(getCurrentId());
1887 private void onEnterZoomView() {
1888 if (mListener != null) {
1889 mListener.onEnterZoomView(getCurrentId());
1893 private void onLeaveZoomView() {
1894 mController.setSurroundingViewsVisible(true);
1898 * MyController controls all the geometry animations. It passively tells the
1899 * geometry information on demand.
1901 private class MyController implements FilmstripController {
1903 private final ValueAnimator mScaleAnimator;
1904 private ValueAnimator mZoomAnimator;
1905 private AnimatorSet mFlingAnimator;
1907 private final MyScroller mScroller;
1908 private boolean mCanStopScroll;
1910 private final MyScroller.Listener mScrollerListener =
1911 new MyScroller.Listener() {
1913 public void onScrollUpdate(int currX, int currY) {
1916 boolean stopScroll = clampCenterX();
1918 mController.stopScrolling(true);
1924 public void onScrollEnd() {
1925 mCanStopScroll = true;
1926 if (mViewItem[mCurrentItem] == null) {
1930 if (isCurrentItemCentered()
1931 && isViewTypeSticky(mViewItem[mCurrentItem])) {
1932 // Special case for the scrolling end on the camera
1939 private final ValueAnimator.AnimatorUpdateListener mScaleAnimatorUpdateListener =
1940 new ValueAnimator.AnimatorUpdateListener() {
1942 public void onAnimationUpdate(ValueAnimator animation) {
1943 if (mViewItem[mCurrentItem] == null) {
1946 mScale = (Float) animation.getAnimatedValue();
1951 MyController(Context context) {
1952 TimeInterpolator decelerateInterpolator = new DecelerateInterpolator(1.5f);
1953 mScroller = new MyScroller(mActivity.getAndroidContext(),
1954 new Handler(mActivity.getMainLooper()),
1955 mScrollerListener, decelerateInterpolator);
1956 mCanStopScroll = true;
1958 mScaleAnimator = new ValueAnimator();
1959 mScaleAnimator.addUpdateListener(mScaleAnimatorUpdateListener);
1960 mScaleAnimator.setInterpolator(decelerateInterpolator);
1961 mScaleAnimator.addListener(new Animator.AnimatorListener() {
1963 public void onAnimationStart(Animator animator) {
1964 if (mScale == FULL_SCREEN_SCALE) {
1965 onLeaveFullScreen();
1967 if (mScale == FILM_STRIP_SCALE) {
1974 public void onAnimationEnd(Animator animator) {
1975 if (mScale == FULL_SCREEN_SCALE) {
1976 onEnterFullScreen();
1978 if (mScale == FILM_STRIP_SCALE) {
1982 zoomAtIndexChanged();
1986 public void onAnimationCancel(Animator animator) {
1991 public void onAnimationRepeat(Animator animator) {
1998 public void setImageGap(int imageGap) {
1999 FilmstripView.this.setViewGap(imageGap);
2003 public int getCurrentId() {
2004 return FilmstripView.this.getCurrentId();
2008 public void setDataAdapter(DataAdapter adapter) {
2009 FilmstripView.this.setDataAdapter(adapter);
2013 public boolean inFilmstrip() {
2014 return FilmstripView.this.inFilmstrip();
2018 public boolean inFullScreen() {
2019 return FilmstripView.this.inFullScreen();
2023 public boolean isCameraPreview() {
2024 return FilmstripView.this.isCameraPreview();
2028 public boolean inCameraFullscreen() {
2029 return FilmstripView.this.inCameraFullscreen();
2033 public void setListener(FilmstripListener l) {
2034 FilmstripView.this.setListener(l);
2038 public boolean isScrolling() {
2039 return !mScroller.isFinished();
2043 public boolean isScaling() {
2044 return mScaleAnimator.isRunning();
2047 private int estimateMinX(int dataID, int leftPos, int viewWidth) {
2048 return leftPos - (dataID + 100) * (viewWidth + mViewGapInPixel);
2051 private int estimateMaxX(int dataID, int leftPos, int viewWidth) {
2053 + (mDataAdapter.getTotalNumber() - dataID + 100)
2054 * (viewWidth + mViewGapInPixel);
2057 /** Zoom all the way in or out on the image at the given pivot point. */
2058 private void zoomAt(final ViewItem current, final float focusX, final float focusY) {
2059 // End previous zoom animation, if any
2060 if (mZoomAnimator != null) {
2061 mZoomAnimator.end();
2063 // Calculate end scale
2064 final float maxScale = getCurrentDataMaxScale(false);
2065 final float endScale = mScale < maxScale - maxScale * TOLERANCE
2066 ? maxScale : FULL_SCREEN_SCALE;
2068 mZoomAnimator = new ValueAnimator();
2069 mZoomAnimator.setFloatValues(mScale, endScale);
2070 mZoomAnimator.setDuration(ZOOM_ANIMATION_DURATION_MS);
2071 mZoomAnimator.addListener(new Animator.AnimatorListener() {
2073 public void onAnimationStart(Animator animation) {
2074 if (mScale == FULL_SCREEN_SCALE) {
2075 if (mFullScreenUIHidden) {
2076 onLeaveFullScreenUiHidden();
2078 onLeaveFullScreen();
2080 setSurroundingViewsVisible(false);
2081 } else if (inZoomView()) {
2084 cancelLoadingZoomedImage();
2088 public void onAnimationEnd(Animator animation) {
2089 // Make sure animation ends up having the correct scale even
2090 // if it is cancelled before it finishes
2091 if (mScale != endScale) {
2092 current.postScale(focusX, focusY, endScale / mScale, mDrawArea.width(),
2093 mDrawArea.height());
2097 if (inFullScreen()) {
2098 setSurroundingViewsVisible(true);
2099 mZoomView.setVisibility(GONE);
2100 current.resetTransform();
2101 onEnterFullScreenUiHidden();
2103 mController.loadZoomedImage();
2106 mZoomAnimator = null;
2107 zoomAtIndexChanged();
2111 public void onAnimationCancel(Animator animation) {
2116 public void onAnimationRepeat(Animator animation) {
2121 mZoomAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
2123 public void onAnimationUpdate(ValueAnimator animation) {
2124 float newScale = (Float) animation.getAnimatedValue();
2125 float postScale = newScale / mScale;
2127 current.postScale(focusX, focusY, postScale, mDrawArea.width(),
2128 mDrawArea.height());
2131 mZoomAnimator.start();
2135 public void scroll(float deltaX) {
2136 if (!stopScrolling(false)) {
2141 boolean stopScroll = clampCenterX();
2143 mController.stopScrolling(true);
2149 public void fling(float velocityX) {
2150 if (!stopScrolling(false)) {
2153 final ViewItem item = mViewItem[mCurrentItem];
2158 float scaledVelocityX = velocityX / mScale;
2159 if (inFullScreen() && isViewTypeSticky(item) && scaledVelocityX < 0) {
2160 // Swipe left in camera preview.
2165 // Estimation of possible length on the left. To ensure the
2166 // velocity doesn't become too slow eventually, we add a huge number
2167 // to the estimated maximum.
2168 int minX = estimateMinX(item.getId(), item.getLeftPosition(), w);
2169 // Estimation of possible length on the right. Likewise, exaggerate
2170 // the possible maximum too.
2171 int maxX = estimateMaxX(item.getId(), item.getLeftPosition(), w);
2172 mScroller.fling(mCenterX, 0, (int) -velocityX, 0, minX, maxX, 0, 0);
2175 void flingInsideZoomView(float velocityX, float velocityY) {
2176 if (!inZoomView()) {
2180 final ViewItem current = mViewItem[mCurrentItem];
2181 if (current == null) {
2185 final int factor = DECELERATION_FACTOR;
2186 // Deceleration curve for distance:
2187 // S(t) = s + (e - s) * (1 - (1 - t/T) ^ factor)
2188 // Need to find the ending distance (e), so that the starting
2189 // velocity is the velocity of fling.
2190 // Velocity is the derivative of distance
2191 // V(t) = (e - s) * factor * (-1) * (1 - t/T) ^ (factor - 1) * (-1/T)
2192 // = (e - s) * factor * (1 - t/T) ^ (factor - 1) / T
2193 // Since V(0) = V0, we have e = T / factor * V0 + s
2195 // Duration T should be long enough so that at the end of the fling,
2196 // image moves at 1 pixel/s for about P = 50ms = 0.05s
2197 // i.e. V(T - P) = 1
2198 // V(T - P) = V0 * (1 - (T -P) /T) ^ (factor - 1) = 1
2199 // T = P * V0 ^ (1 / (factor -1))
2201 final float velocity = Math.max(Math.abs(velocityX), Math.abs(velocityY));
2202 // Dynamically calculate duration
2203 final float duration = (float) (FLING_COASTING_DURATION_S
2204 * Math.pow(velocity, (1f / (factor - 1f))));
2206 final float translationX = current.getTranslationX() * mScale;
2207 final float translationY = current.getTranslationY() * mScale;
2209 final ValueAnimator decelerationX = ValueAnimator.ofFloat(translationX,
2210 translationX + duration / factor * velocityX);
2211 final ValueAnimator decelerationY = ValueAnimator.ofFloat(translationY,
2212 translationY + duration / factor * velocityY);
2214 decelerationY.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
2216 public void onAnimationUpdate(ValueAnimator animation) {
2217 float transX = (Float) decelerationX.getAnimatedValue();
2218 float transY = (Float) decelerationY.getAnimatedValue();
2220 current.updateTransform(transX, transY, mScale,
2221 mScale, mDrawArea.width(), mDrawArea.height());
2225 mFlingAnimator = new AnimatorSet();
2226 mFlingAnimator.play(decelerationX).with(decelerationY);
2227 mFlingAnimator.setDuration((int) (duration * 1000));
2228 mFlingAnimator.setInterpolator(new TimeInterpolator() {
2230 public float getInterpolation(float input) {
2231 return (float) (1.0f - Math.pow((1.0f - input), factor));
2234 mFlingAnimator.addListener(new Animator.AnimatorListener() {
2235 private boolean mCancelled = false;
2238 public void onAnimationStart(Animator animation) {
2243 public void onAnimationEnd(Animator animation) {
2247 mFlingAnimator = null;
2251 public void onAnimationCancel(Animator animation) {
2256 public void onAnimationRepeat(Animator animation) {
2260 mFlingAnimator.start();
2264 public boolean stopScrolling(boolean forced) {
2265 if (!isScrolling()) {
2267 } else if (!mCanStopScroll && !forced) {
2270 mScroller.forceFinished(true);
2274 private void stopScale() {
2275 mScaleAnimator.cancel();
2279 public void scrollToPosition(int position, int duration, boolean interruptible) {
2280 if (mViewItem[mCurrentItem] == null) {
2283 mCanStopScroll = interruptible;
2284 mScroller.startScroll(mCenterX, 0, position - mCenterX, 0, duration);
2288 public boolean goToNextItem() {
2289 return goToItem(mCurrentItem + 1);
2293 public boolean goToPreviousItem() {
2294 return goToItem(mCurrentItem - 1);
2297 private boolean goToItem(int itemIndex) {
2298 final ViewItem nextItem = mViewItem[itemIndex];
2299 if (nextItem == null) {
2302 stopScrolling(true);
2303 scrollToPosition(nextItem.getCenterX(), GEOMETRY_ADJUST_TIME_MS * 2, false);
2305 if (isViewTypeSticky(mViewItem[mCurrentItem])) {
2306 // Special case when moving from camera preview.
2307 scaleTo(FILM_STRIP_SCALE, GEOMETRY_ADJUST_TIME_MS);
2312 private void scaleTo(float scale, int duration) {
2313 if (mViewItem[mCurrentItem] == null) {
2317 mScaleAnimator.setDuration(duration);
2318 mScaleAnimator.setFloatValues(mScale, scale);
2319 mScaleAnimator.start();
2323 public void goToFilmstrip() {
2324 if (mViewItem[mCurrentItem] == null) {
2327 if (mScale == FILM_STRIP_SCALE) {
2330 scaleTo(FILM_STRIP_SCALE, GEOMETRY_ADJUST_TIME_MS);
2332 final ViewItem currItem = mViewItem[mCurrentItem];
2333 final ViewItem nextItem = mViewItem[mCurrentItem + 1];
2334 if (currItem.getId() == 0 && isViewTypeSticky(currItem) && nextItem != null) {
2335 // Deal with the special case of swiping in camera preview.
2336 scrollToPosition(nextItem.getCenterX(), GEOMETRY_ADJUST_TIME_MS, false);
2339 if (mScale == FILM_STRIP_SCALE) {
2345 public void goToFullScreen() {
2346 if (inFullScreen()) {
2350 scaleTo(FULL_SCREEN_SCALE, GEOMETRY_ADJUST_TIME_MS);
2353 private void cancelFlingAnimation() {
2354 // Cancels flinging for zoomed images
2355 if (isFlingAnimationRunning()) {
2356 mFlingAnimator.cancel();
2360 private void cancelZoomAnimation() {
2361 if (isZoomAnimationRunning()) {
2362 mZoomAnimator.cancel();
2366 private void setSurroundingViewsVisible(boolean visible) {
2367 // Hide everything on the left
2368 // TODO: Need to find a better way to toggle the visibility of views
2369 // around the current view.
2370 for (int i = 0; i < mCurrentItem; i++) {
2371 if (i == mCurrentItem || mViewItem[i] == null) {
2374 mViewItem[i].setVisibility(visible ? VISIBLE : INVISIBLE);
2378 private Uri getCurrentUri() {
2379 ViewItem curr = mViewItem[mCurrentItem];
2383 return mDataAdapter.getImageData(curr.getId()).getUri();
2387 * Here we only support up to 1:1 image zoom (i.e. a 100% view of the
2388 * actual pixels). The max scale that we can apply on the view should
2389 * make the view same size as the image, in pixels.
2391 private float getCurrentDataMaxScale(boolean allowOverScale) {
2392 ViewItem curr = mViewItem[mCurrentItem];
2394 return FULL_SCREEN_SCALE;
2396 ImageData imageData = mDataAdapter.getImageData(curr.getId());
2397 if (imageData == null || !imageData.isUIActionSupported(ImageData.ACTION_ZOOM)) {
2398 return FULL_SCREEN_SCALE;
2400 float imageWidth = imageData.getWidth();
2401 if (imageData.getRotation() == 90
2402 || imageData.getRotation() == 270) {
2403 imageWidth = imageData.getHeight();
2405 float scale = imageWidth / curr.getWidth();
2406 if (allowOverScale) {
2407 // In addition to the scale we apply to the view for 100% view
2408 // (i.e. each pixel on screen corresponds to a pixel in image)
2409 // we allow scaling beyond that for better detail viewing.
2410 scale *= mOverScaleFactor;
2415 private void loadZoomedImage() {
2416 if (!inZoomView()) {
2419 ViewItem curr = mViewItem[mCurrentItem];
2423 ImageData imageData = mDataAdapter.getImageData(curr.getId());
2424 if (!imageData.isUIActionSupported(ImageData.ACTION_ZOOM)) {
2427 Uri uri = getCurrentUri();
2428 RectF viewRect = curr.getViewRect();
2429 if (uri == null || uri == Uri.EMPTY) {
2432 int orientation = imageData.getRotation();
2433 mZoomView.loadBitmap(uri, orientation, viewRect);
2436 private void cancelLoadingZoomedImage() {
2437 mZoomView.cancelPartialDecodingTask();
2441 public void goToFirstItem() {
2442 if (mViewItem[mCurrentItem] == null) {
2446 // TODO: animate to camera if it is still in the mViewItem buffer
2447 // versus a full reload which will perform an immediate transition
2451 public boolean inZoomView() {
2452 return FilmstripView.this.inZoomView();
2455 public boolean isFlingAnimationRunning() {
2456 return mFlingAnimator != null && mFlingAnimator.isRunning();
2459 public boolean isZoomAnimationRunning() {
2460 return mZoomAnimator != null && mZoomAnimator.isRunning();
2464 private boolean isCurrentItemCentered() {
2465 return mViewItem[mCurrentItem].getCenterX() == mCenterX;
2468 private static class MyScroller {
2469 public interface Listener {
2470 public void onScrollUpdate(int currX, int currY);
2472 public void onScrollEnd();
2475 private final Handler mHandler;
2476 private final Listener mListener;
2478 private final Scroller mScroller;
2480 private final ValueAnimator mXScrollAnimator;
2481 private final Runnable mScrollChecker = new Runnable() {
2484 boolean newPosition = mScroller.computeScrollOffset();
2486 mListener.onScrollEnd();
2489 mListener.onScrollUpdate(mScroller.getCurrX(), mScroller.getCurrY());
2490 mHandler.removeCallbacks(this);
2491 mHandler.post(this);
2495 private final ValueAnimator.AnimatorUpdateListener mXScrollAnimatorUpdateListener =
2496 new ValueAnimator.AnimatorUpdateListener() {
2498 public void onAnimationUpdate(ValueAnimator animation) {
2499 mListener.onScrollUpdate((Integer) animation.getAnimatedValue(), 0);
2503 private final Animator.AnimatorListener mXScrollAnimatorListener =
2504 new Animator.AnimatorListener() {
2506 public void onAnimationCancel(Animator animation) {
2511 public void onAnimationEnd(Animator animation) {
2512 mListener.onScrollEnd();
2516 public void onAnimationRepeat(Animator animation) {
2521 public void onAnimationStart(Animator animation) {
2526 public MyScroller(Context ctx, Handler handler, Listener listener,
2527 TimeInterpolator interpolator) {
2529 mListener = listener;
2530 mScroller = new Scroller(ctx);
2531 mXScrollAnimator = new ValueAnimator();
2532 mXScrollAnimator.addUpdateListener(mXScrollAnimatorUpdateListener);
2533 mXScrollAnimator.addListener(mXScrollAnimatorListener);
2534 mXScrollAnimator.setInterpolator(interpolator);
2538 int startX, int startY,
2539 int velocityX, int velocityY,
2541 int minY, int maxY) {
2542 mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY);
2546 public void startScroll(int startX, int startY, int dx, int dy) {
2547 mScroller.startScroll(startX, startY, dx, dy);
2551 /** Only starts and updates scroll in x-axis. */
2552 public void startScroll(int startX, int startY, int dx, int dy, int duration) {
2553 mXScrollAnimator.cancel();
2554 mXScrollAnimator.setDuration(duration);
2555 mXScrollAnimator.setIntValues(startX, startX + dx);
2556 mXScrollAnimator.start();
2559 public boolean isFinished() {
2560 return (mScroller.isFinished() && !mXScrollAnimator.isRunning());
2563 public void forceFinished(boolean finished) {
2564 mScroller.forceFinished(finished);
2566 mXScrollAnimator.cancel();
2570 private void runChecker() {
2571 if (mHandler == null || mListener == null) {
2574 mHandler.removeCallbacks(mScrollChecker);
2575 mHandler.post(mScrollChecker);
2579 private class MyGestureReceiver implements FilmstripGestureRecognizer.Listener {
2581 private static final int SCROLL_DIR_NONE = 0;
2582 private static final int SCROLL_DIR_VERTICAL = 1;
2583 private static final int SCROLL_DIR_HORIZONTAL = 2;
2584 // Indicating the current trend of scaling is up (>1) or down (<1).
2585 private float mScaleTrend;
2586 private float mMaxScale;
2587 private int mScrollingDirection = SCROLL_DIR_NONE;
2588 private long mLastDownTime;
2589 private float mLastDownY;
2592 public boolean onSingleTapUp(float x, float y) {
2593 ViewItem centerItem = mViewItem[mCurrentItem];
2594 if (inFilmstrip()) {
2595 if (centerItem != null && centerItem.areaContains(x, y)) {
2596 mController.goToFullScreen();
2599 } else if (inFullScreen()) {
2600 if (mFullScreenUIHidden) {
2601 onLeaveFullScreenUiHidden();
2602 onEnterFullScreen();
2604 onLeaveFullScreen();
2605 onEnterFullScreenUiHidden();
2613 public boolean onDoubleTap(float x, float y) {
2614 ViewItem current = mViewItem[mCurrentItem];
2615 if (current == null) {
2618 if (inFilmstrip()) {
2619 mController.goToFullScreen();
2621 } else if (mScale < FULL_SCREEN_SCALE || inCameraFullscreen()) {
2624 if (!mController.stopScrolling(false)) {
2627 if (inFullScreen()) {
2628 mController.zoomAt(current, x, y);
2629 checkItemAtMaxSize();
2631 } else if (mScale > FULL_SCREEN_SCALE) {
2633 mController.zoomAt(current, x, y);
2639 public boolean onDown(float x, float y) {
2640 mLastDownTime = SystemClock.uptimeMillis();
2642 mController.cancelFlingAnimation();
2643 if (!mController.stopScrolling(false)) {
2651 public boolean onUp(float x, float y) {
2652 ViewItem currItem = mViewItem[mCurrentItem];
2653 if (currItem == null) {
2656 if (mController.isZoomAnimationRunning() || mController.isFlingAnimationRunning()) {
2660 mController.loadZoomedImage();
2663 float promoteHeight = getHeight() * PROMOTE_HEIGHT_RATIO;
2664 float velocityPromoteHeight = getHeight() * VELOCITY_PROMOTE_HEIGHT_RATIO;
2665 mIsUserScrolling = false;
2666 mScrollingDirection = SCROLL_DIR_NONE;
2667 // Finds items promoted/demoted.
2668 float speedY = Math.abs(y - mLastDownY)
2669 / (SystemClock.uptimeMillis() - mLastDownTime);
2670 for (int i = 0; i < BUFFER_SIZE; i++) {
2671 if (mViewItem[i] == null) {
2674 float transY = mViewItem[i].getTranslationY();
2678 int id = mViewItem[i].getId();
2680 if (mDataAdapter.getImageData(id)
2681 .isUIActionSupported(ImageData.ACTION_DEMOTE)
2682 && ((transY > promoteHeight)
2683 || (transY > velocityPromoteHeight && speedY > PROMOTE_VELOCITY))) {
2685 } else if (mDataAdapter.getImageData(id)
2686 .isUIActionSupported(ImageData.ACTION_PROMOTE)
2687 && (transY < -promoteHeight
2688 || (transY < -velocityPromoteHeight && speedY > PROMOTE_VELOCITY))) {
2691 // put the view back.
2692 slideViewBack(mViewItem[i]);
2696 // The data might be changed. Re-check.
2697 currItem = mViewItem[mCurrentItem];
2698 if (currItem == null) {
2702 int currId = currItem.getId();
2703 if (mCenterX > currItem.getCenterX() + CAMERA_PREVIEW_SWIPE_THRESHOLD && currId == 0 &&
2704 isViewTypeSticky(currItem) && mDataIdOnUserScrolling == 0) {
2705 mController.goToFilmstrip();
2706 // Special case to go from camera preview to the next photo.
2707 if (mViewItem[mCurrentItem + 1] != null) {
2708 mController.scrollToPosition(
2709 mViewItem[mCurrentItem + 1].getCenterX(),
2710 GEOMETRY_ADJUST_TIME_MS, false);
2716 if (isCurrentItemCentered() && currId == 0 && isViewTypeSticky(currItem)) {
2717 mController.goToFullScreen();
2719 if (mDataIdOnUserScrolling == 0 && currId != 0) {
2720 // Special case to go to filmstrip when the user scroll away
2721 // from the camera preview and the current one is not the
2723 mController.goToFilmstrip();
2724 mDataIdOnUserScrolling = currId;
2732 public void onLongPress(float x, float y) {
2733 final int dataId = getCurrentId();
2737 mListener.onFocusedDataLongPressed(dataId);
2741 public boolean onScroll(float x, float y, float dx, float dy) {
2742 final ViewItem currItem = mViewItem[mCurrentItem];
2743 if (currItem == null) {
2746 if (inFullScreen() && !mDataAdapter.canSwipeInFullScreen(currItem.getId())) {
2750 // When image is zoomed in to be bigger than the screen
2752 ViewItem curr = mViewItem[mCurrentItem];
2753 float transX = curr.getTranslationX() * mScale - dx;
2754 float transY = curr.getTranslationY() * mScale - dy;
2755 curr.updateTransform(transX, transY, mScale, mScale, mDrawArea.width(),
2756 mDrawArea.height());
2759 int deltaX = (int) (dx / mScale);
2760 // Forces the current scrolling to stop.
2761 mController.stopScrolling(true);
2762 if (!mIsUserScrolling) {
2763 mIsUserScrolling = true;
2764 mDataIdOnUserScrolling = mViewItem[mCurrentItem].getId();
2766 if (inFilmstrip()) {
2767 // Disambiguate horizontal/vertical first.
2768 if (mScrollingDirection == SCROLL_DIR_NONE) {
2769 mScrollingDirection = (Math.abs(dx) > Math.abs(dy)) ? SCROLL_DIR_HORIZONTAL :
2770 SCROLL_DIR_VERTICAL;
2772 if (mScrollingDirection == SCROLL_DIR_HORIZONTAL) {
2773 if (mCenterX == currItem.getCenterX() && currItem.getId() == 0 && dx < 0) {
2774 // Already at the beginning, don't process the swipe.
2775 mIsUserScrolling = false;
2776 mScrollingDirection = SCROLL_DIR_NONE;
2779 mController.scroll(deltaX);
2781 // Vertical part. Promote or demote.
2783 Rect hitRect = new Rect();
2784 for (; hit < BUFFER_SIZE; hit++) {
2785 if (mViewItem[hit] == null) {
2788 mViewItem[hit].getHitRect(hitRect);
2789 if (hitRect.contains((int) x, (int) y)) {
2793 if (hit == BUFFER_SIZE) {
2798 ImageData data = mDataAdapter.getImageData(mViewItem[hit].getId());
2799 float transY = mViewItem[hit].getTranslationY() - dy / mScale;
2800 if (!data.isUIActionSupported(ImageData.ACTION_DEMOTE) &&
2804 if (!data.isUIActionSupported(ImageData.ACTION_PROMOTE) &&
2808 mViewItem[hit].setTranslationY(transY);
2810 } else if (inFullScreen()) {
2811 if (mViewItem[mCurrentItem] == null || (deltaX < 0 && mCenterX <=
2812 currItem.getCenterX() && currItem.getId() == 0)) {
2815 // Multiplied by 1.2 to make it more easy to swipe.
2816 mController.scroll((int) (deltaX * 1.2));
2824 public boolean onMouseScroll(float hscroll, float vscroll) {
2827 hscroll *= MOUSE_SCROLL_FACTOR;
2828 vscroll *= MOUSE_SCROLL_FACTOR;
2830 if (vscroll != 0f) {
2836 if (inFullScreen()) {
2837 onFling(-scroll, 0f);
2838 } else if (inZoomView()) {
2839 onScroll(0f, 0f, hscroll, vscroll);
2841 onScroll(0f, 0f, scroll, 0f);
2848 public boolean onFling(float velocityX, float velocityY) {
2849 final ViewItem currItem = mViewItem[mCurrentItem];
2850 if (currItem == null) {
2853 if (!mDataAdapter.canSwipeInFullScreen(currItem.getId())) {
2857 // Fling within the zoomed image
2858 mController.flingInsideZoomView(velocityX, velocityY);
2861 if (Math.abs(velocityX) < Math.abs(velocityY)) {
2862 // ignore vertical fling.
2866 // In full-screen, fling of a velocity above a threshold should go
2867 // to the next/prev photos
2868 if (mScale == FULL_SCREEN_SCALE) {
2869 int currItemCenterX = currItem.getCenterX();
2871 if (velocityX > 0) { // left
2872 if (mCenterX > currItemCenterX) {
2873 // The visually previous item is actually the current
2875 mController.scrollToPosition(
2876 currItemCenterX, GEOMETRY_ADJUST_TIME_MS, true);
2879 ViewItem prevItem = mViewItem[mCurrentItem - 1];
2880 if (prevItem == null) {
2883 mController.scrollToPosition(
2884 prevItem.getCenterX(), GEOMETRY_ADJUST_TIME_MS, true);
2886 if (mController.stopScrolling(false)) {
2887 if (mCenterX < currItemCenterX) {
2888 // The visually next item is actually the current
2890 mController.scrollToPosition(
2891 currItemCenterX, GEOMETRY_ADJUST_TIME_MS, true);
2894 final ViewItem nextItem = mViewItem[mCurrentItem + 1];
2895 if (nextItem == null) {
2898 mController.scrollToPosition(
2899 nextItem.getCenterX(), GEOMETRY_ADJUST_TIME_MS, true);
2900 if (isViewTypeSticky(currItem)) {
2901 mController.goToFilmstrip();
2907 if (mScale == FILM_STRIP_SCALE) {
2908 mController.fling(velocityX);
2914 public boolean onScaleBegin(float focusX, float focusY) {
2915 if (inCameraFullscreen()) {
2921 // If the image is smaller than screen size, we should allow to zoom
2922 // in to full screen size
2923 mMaxScale = Math.max(mController.getCurrentDataMaxScale(true), FULL_SCREEN_SCALE);
2928 public boolean onScale(float focusX, float focusY, float scale) {
2929 if (inCameraFullscreen()) {
2933 mScaleTrend = mScaleTrend * 0.3f + scale * 0.7f;
2934 float newScale = mScale * scale;
2935 if (mScale < FULL_SCREEN_SCALE && newScale < FULL_SCREEN_SCALE) {
2936 if (newScale <= FILM_STRIP_SCALE) {
2937 newScale = FILM_STRIP_SCALE;
2939 // Scaled view is smaller than or equal to screen size both
2940 // before and after scaling
2941 if (mScale != newScale) {
2942 if (mScale == FILM_STRIP_SCALE) {
2945 if (newScale == FILM_STRIP_SCALE) {
2951 } else if (mScale < FULL_SCREEN_SCALE && newScale >= FULL_SCREEN_SCALE) {
2952 // Going from smaller than screen size to bigger than or equal
2954 if (mScale == FILM_STRIP_SCALE) {
2957 mScale = FULL_SCREEN_SCALE;
2958 onEnterFullScreen();
2959 mController.setSurroundingViewsVisible(false);
2961 } else if (mScale >= FULL_SCREEN_SCALE && newScale < FULL_SCREEN_SCALE) {
2962 // Going from bigger than or equal to screen size to smaller
2964 if (inFullScreen()) {
2965 if (mFullScreenUIHidden) {
2966 onLeaveFullScreenUiHidden();
2968 onLeaveFullScreen();
2977 // Scaled view bigger than or equal to screen size both before
2978 // and after scaling
2979 if (!inZoomView()) {
2980 mController.setSurroundingViewsVisible(false);
2982 ViewItem curr = mViewItem[mCurrentItem];
2983 // Make sure the image is not overly scaled
2984 newScale = Math.min(newScale, mMaxScale);
2985 if (newScale == mScale) {
2988 float postScale = newScale / mScale;
2989 curr.postScale(focusX, focusY, postScale, mDrawArea.width(), mDrawArea.height());
2991 if (mScale == FULL_SCREEN_SCALE) {
2992 onEnterFullScreen();
2996 checkItemAtMaxSize();
3002 public void onScaleEnd() {
3003 zoomAtIndexChanged();
3004 if (mScale > FULL_SCREEN_SCALE + TOLERANCE) {
3007 mController.setSurroundingViewsVisible(true);
3008 if (mScale <= FILM_STRIP_SCALE + TOLERANCE) {
3009 mController.goToFilmstrip();
3010 } else if (mScaleTrend > 1f || mScale > FULL_SCREEN_SCALE - TOLERANCE) {
3012 mScale = FULL_SCREEN_SCALE;
3015 mController.goToFullScreen();
3017 mController.goToFilmstrip();