* When using a translucent status bar on API 19+, the window will not
* resize to make room for input methods (i.e.
* {@link android.view.WindowManager.LayoutParams#SOFT_INPUT_ADJUST_RESIZE} and
* {@link android.view.WindowManager.LayoutParams#SOFT_INPUT_ADJUST_PAN} are
* ignored).
*
* To work around this; override {@link #fitSystemWindows(Rect)},
* capture and override the system insets, and then call through to FrameLayout's
* implementation.
*
* For reasons yet unknown, modifying the bottom inset causes this workaround to
* fail. Modifying the top, left, and right insets works as expected.
*/
public final class FixInsetsFrameLayout extends FrameLayout {
private int[] mInsets = new int[4];
public FixInsetsFrameLayout(Context context) {
super(context);
}
public FixInsetsFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FixInsetsFrameLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private boolean insetEnable = false;
public void setInsetEnable(boolean insetEnable) {
this.insetEnable = insetEnable;
}
@Override
protected final boolean fitSystemWindows(Rect insets) {
if (!insetEnable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Intentionally do not modify the bottom inset. For some reason,
// if the bottom inset is modified, window resizing stops working.
mInsets[0] = insets.left;
mInsets[1] = insets.top;
mInsets[2] = insets.right;
insets.left = 0;
insets.top = 0;
insets.right = 0;
}
return super.fitSystemWindows(insets);
}
@Override
public final WindowInsets onApplyWindowInsets(WindowInsets insets) {
if (!insetEnable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mInsets[0] = insets.getSystemWindowInsetLeft();
mInsets[1] = insets.getSystemWindowInsetTop();
mInsets[2] = insets.getSystemWindowInsetRight();
return super.onApplyWindowInsets(insets.replaceSystemWindowInsets(0, 0, 0,
insets.getSystemWindowInsetBottom()));
} else {
return insets;
}
}
}
================================================
FILE: hydrogen-library/src/main/java/androlua/widget/statusbar/StatusBarView.java
================================================
package androlua.widget.statusbar;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
/**
* StatusBarView
* Created by hanks on 18-4-17.
*/
public class StatusBarView extends View {
private int statusBarColor;
private int statusBarHeight;
public StatusBarView(Context context) {
this(context, null);
}
public StatusBarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public StatusBarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
statusBarColor = Color.BLACK;
statusBarHeight = getStatusBarHeight(context);
}
public void setStatusBarColor(int statusBarColor) {
this.statusBarColor = statusBarColor;
invalidate();
}
public void setStatusBarHeight(int statusBarHeight) {
this.statusBarHeight = statusBarHeight;
getLayoutParams().height = statusBarHeight;
requestLayout();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(statusBarColor);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(widthMeasureSpec, statusBarHeight);
}
private int getStatusBarHeight(Context context) {
if (Build.VERSION.SDK_INT < 21) {
return 0;
}
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
private int getNavigationBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
}
================================================
FILE: hydrogen-library/src/main/java/androlua/widget/swipebacklayout/SwipeBackLayout.java
================================================
package androlua.widget.swipebacklayout;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import java.util.ArrayList;
import java.util.List;
import pub.hanks.luajandroid.R;
public class SwipeBackLayout extends FrameLayout {
/**
* Edge flag indicating that the left edge should be affected.
*/
public static final int EDGE_LEFT = ViewDragHelper.EDGE_LEFT;
/**
* Edge flag indicating that the right edge should be affected.
*/
public static final int EDGE_RIGHT = ViewDragHelper.EDGE_RIGHT;
/**
* Edge flag indicating that the bottom edge should be affected.
*/
public static final int EDGE_BOTTOM = ViewDragHelper.EDGE_BOTTOM;
/**
* Edge flag set indicating all edges should be affected.
*/
public static final int EDGE_ALL = EDGE_LEFT | EDGE_RIGHT | EDGE_BOTTOM;
/**
* A view is not currently being dragged or animating as a result of a
* fling/snap.
*/
public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE;
/**
* A view is currently being dragged. The position is currently changing as
* a result of user input or simulated user input.
*/
public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING;
/**
* A view is currently settling into place as a result of a fling or
* predefined non-interactive motion.
*/
public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING;
/**
* Minimum velocity that will be detected as a fling
*/
private static final int MIN_FLING_VELOCITY = 400; // dips per second
private static final int DEFAULT_SCRIM_COLOR = 0x99000000;
private static final int FULL_ALPHA = 255;
/**
* Default threshold of scroll
*/
private static final float DEFAULT_SCROLL_THRESHOLD = 0.3f;
private static final int OVERSCROLL_DISTANCE = 10;
private static final int[] EDGE_FLAGS = {
EDGE_LEFT, EDGE_RIGHT, EDGE_BOTTOM, EDGE_ALL
};
private int mEdgeFlag;
/**
* Threshold of scroll, we will close the activity, when scrollPercent over
* this value;
*/
private float mScrollThreshold = DEFAULT_SCROLL_THRESHOLD;
private Activity mActivity;
private boolean mEnable = true;
private View mContentView;
private ViewDragHelper mDragHelper;
private float mScrollPercent;
private int mContentLeft;
private int mContentTop;
/**
* The set of listeners to be sent events through.
*/
private List mListeners;
private Drawable mShadowLeft;
private Drawable mShadowRight;
private Drawable mShadowBottom;
private float mScrimOpacity;
private int mScrimColor = DEFAULT_SCRIM_COLOR;
private boolean mInLayout;
private Rect mTmpRect = new Rect();
/**
* Edge being dragged
*/
private int mTrackingEdge;
public SwipeBackLayout(Context context) {
this(context, null);
}
public SwipeBackLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SwipeBackLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs);
mDragHelper = ViewDragHelper.create(this, new ViewDragCallback());
setEdgeSize(dp2px(50));
int mode = EDGE_FLAGS[0];
setEdgeTrackingEnabled(mode);
int shadowLeft = R.drawable.shadow_left;
int shadowRight = R.drawable.shadow_right;
int shadowBottom = R.drawable.shadow_bottom;
setShadow(shadowLeft, EDGE_LEFT);
setShadow(shadowRight, EDGE_RIGHT);
setShadow(shadowBottom, EDGE_BOTTOM);
final float density = getResources().getDisplayMetrics().density;
final float minVel = MIN_FLING_VELOCITY * density;
mDragHelper.setMinVelocity(minVel);
mDragHelper.setMaxVelocity(minVel * 2f);
}
private int dp2px(float dp) {
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics);
}
/**
* Sets the sensitivity of the NavigationLayout.
*
* @param context The application context.
* @param sensitivity value between 0 and 1, the final value for touchSlop =
* ViewConfiguration.getScaledTouchSlop * (1 / s);
*/
public void setSensitivity(Context context, float sensitivity) {
mDragHelper.setSensitivity(context, sensitivity);
}
/**
* Set up contentView which will be moved by user gesture
*
* @param view
*/
private void setContentView(View view) {
mContentView = view;
}
public void setEnableGesture(boolean enable) {
mEnable = enable;
}
/**
* Enable edge tracking for the selected edges of the parent view. The
* callback's
* {@link ViewDragHelper.Callback#onEdgeTouched(int, int)}
* and
* {@link ViewDragHelper.Callback#onEdgeDragStarted(int, int)}
* methods will only be invoked for edges for which edge tracking has been
* enabled.
*
* @param edgeFlags Combination of edge flags describing the edges to watch
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void setEdgeTrackingEnabled(int edgeFlags) {
mEdgeFlag = edgeFlags;
mDragHelper.setEdgeTrackingEnabled(mEdgeFlag);
}
/**
* Set a color to use for the scrim that obscures primary content while a
* drawer is open.
*
* @param color Color to use in 0xAARRGGBB format.
*/
public void setScrimColor(int color) {
mScrimColor = color;
invalidate();
}
/**
* Set the size of an edge. This is the range in pixels along the edges of
* this view that will actively detect edge touches or drags if edge
* tracking is enabled.
*
* @param size The size of an edge in pixels
*/
public void setEdgeSize(int size) {
mDragHelper.setEdgeSize(size);
}
/**
* Register a callback to be invoked when a swipe event is sent to this
* view.
*
* @param listener the swipe listener to attach to this view
* @deprecated use {@link #addSwipeListener} instead
*/
@Deprecated
public void setSwipeListener(SwipeListener listener) {
addSwipeListener(listener);
}
/**
* Add a callback to be invoked when a swipe event is sent to this view.
*
* @param listener the swipe listener to attach to this view
*/
public void addSwipeListener(SwipeListener listener) {
if (mListeners == null) {
mListeners = new ArrayList();
}
mListeners.add(listener);
}
/**
* Removes a listener from the set of listeners
*
* @param listener
*/
public void removeSwipeListener(SwipeListener listener) {
if (mListeners == null) {
return;
}
mListeners.remove(listener);
}
/**
* Set scroll threshold, we will close the activity, when scrollPercent over
* this value
*
* @param threshold
*/
public void setScrollThresHold(float threshold) {
if (threshold >= 1.0f || threshold <= 0) {
throw new IllegalArgumentException("Threshold value should be between 0 and 1.0");
}
mScrollThreshold = threshold;
}
/**
* Set a drawable used for edge shadow.
*
* @param shadow Drawable to use
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void setShadow(Drawable shadow, int edgeFlag) {
if ((edgeFlag & EDGE_LEFT) != 0) {
mShadowLeft = shadow;
} else if ((edgeFlag & EDGE_RIGHT) != 0) {
mShadowRight = shadow;
} else if ((edgeFlag & EDGE_BOTTOM) != 0) {
mShadowBottom = shadow;
}
invalidate();
}
/**
* Set a drawable used for edge shadow.
*
* @param resId Resource of drawable to use
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void setShadow(int resId, int edgeFlag) {
setShadow(getResources().getDrawable(resId), edgeFlag);
}
/**
* Scroll out contentView and finish the activity
*/
public void scrollToFinishActivity() {
final int childWidth = mContentView.getWidth();
final int childHeight = mContentView.getHeight();
int left = 0, top = 0;
if ((mEdgeFlag & EDGE_LEFT) != 0) {
left = childWidth + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE;
mTrackingEdge = EDGE_LEFT;
} else if ((mEdgeFlag & EDGE_RIGHT) != 0) {
left = -childWidth - mShadowRight.getIntrinsicWidth() - OVERSCROLL_DISTANCE;
mTrackingEdge = EDGE_RIGHT;
} else if ((mEdgeFlag & EDGE_BOTTOM) != 0) {
top = -childHeight - mShadowBottom.getIntrinsicHeight() - OVERSCROLL_DISTANCE;
mTrackingEdge = EDGE_BOTTOM;
}
mDragHelper.smoothSlideViewTo(mContentView, left, top);
invalidate();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (!mEnable) {
return false;
}
try {
return mDragHelper.shouldInterceptTouchEvent(event);
} catch (ArrayIndexOutOfBoundsException e) {
// FIXME: handle exception
// issues #9
return false;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!mEnable) {
return false;
}
mDragHelper.processTouchEvent(event);
return true;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
mInLayout = true;
if (mContentView != null)
mContentView.layout(mContentLeft, mContentTop,
mContentLeft + mContentView.getMeasuredWidth(),
mContentTop + mContentView.getMeasuredHeight());
mInLayout = false;
}
@Override
public void requestLayout() {
if (!mInLayout) {
super.requestLayout();
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
final boolean drawContent = child == mContentView;
boolean ret = super.drawChild(canvas, child, drawingTime);
if (mScrimOpacity > 0 && drawContent
&& mDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE) {
drawShadow(canvas, child);
drawScrim(canvas, child);
}
return ret;
}
private void drawScrim(Canvas canvas, View child) {
final int baseAlpha = (mScrimColor & 0xff000000) >>> 24;
final int alpha = (int) (baseAlpha * mScrimOpacity);
final int color = alpha << 24 | (mScrimColor & 0xffffff);
if ((mTrackingEdge & EDGE_LEFT) != 0) {
canvas.clipRect(0, 0, child.getLeft(), getHeight());
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
canvas.clipRect(child.getRight(), 0, getRight(), getHeight());
} else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
canvas.clipRect(child.getLeft(), child.getBottom(), getRight(), getHeight());
}
canvas.drawColor(color);
}
private void drawShadow(Canvas canvas, View child) {
final Rect childRect = mTmpRect;
child.getHitRect(childRect);
if ((mEdgeFlag & EDGE_LEFT) != 0) {
mShadowLeft.setBounds(childRect.left - mShadowLeft.getIntrinsicWidth(), childRect.top,
childRect.left, childRect.bottom);
mShadowLeft.setAlpha((int) (mScrimOpacity * FULL_ALPHA));
mShadowLeft.draw(canvas);
}
if ((mEdgeFlag & EDGE_RIGHT) != 0) {
mShadowRight.setBounds(childRect.right, childRect.top,
childRect.right + mShadowRight.getIntrinsicWidth(), childRect.bottom);
mShadowRight.setAlpha((int) (mScrimOpacity * FULL_ALPHA));
mShadowRight.draw(canvas);
}
if ((mEdgeFlag & EDGE_BOTTOM) != 0) {
mShadowBottom.setBounds(childRect.left, childRect.bottom, childRect.right,
childRect.bottom + mShadowBottom.getIntrinsicHeight());
mShadowBottom.setAlpha((int) (mScrimOpacity * FULL_ALPHA));
mShadowBottom.draw(canvas);
}
}
public void attachToActivity(Activity activity) {
mActivity = activity;
TypedArray a = activity.getTheme().obtainStyledAttributes(new int[]{
android.R.attr.windowBackground
});
int background = a.getResourceId(0, 0);
a.recycle();
ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
decorChild.setBackgroundResource(background);
decor.removeView(decorChild);
addView(decorChild);
setContentView(decorChild);
decor.addView(this);
}
@Override
public void computeScroll() {
mScrimOpacity = 1 - mScrollPercent;
if (mDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
public static interface SwipeListener {
/**
* Invoke when state change
*
* @param state flag to describe scroll state
* @param scrollPercent scroll percent of this view
* @see #STATE_IDLE
* @see #STATE_DRAGGING
* @see #STATE_SETTLING
*/
public void onScrollStateChange(int state, float scrollPercent);
/**
* Invoke when edge touched
*
* @param edgeFlag edge flag describing the edge being touched
* @see #EDGE_LEFT
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void onEdgeTouch(int edgeFlag);
/**
* Invoke when scroll percent over the threshold for the first time
*/
public void onScrollOverThreshold();
}
private class ViewDragCallback extends ViewDragHelper.Callback {
private boolean mIsScrollOverValid;
@Override
public boolean tryCaptureView(View view, int i) {
boolean ret = mDragHelper.isEdgeTouched(mEdgeFlag, i);
if (ret) {
if (mDragHelper.isEdgeTouched(EDGE_LEFT, i)) {
mTrackingEdge = EDGE_LEFT;
} else if (mDragHelper.isEdgeTouched(EDGE_RIGHT, i)) {
mTrackingEdge = EDGE_RIGHT;
} else if (mDragHelper.isEdgeTouched(EDGE_BOTTOM, i)) {
mTrackingEdge = EDGE_BOTTOM;
}
if (mListeners != null && !mListeners.isEmpty()) {
for (SwipeListener listener : mListeners) {
listener.onEdgeTouch(mTrackingEdge);
}
}
mIsScrollOverValid = true;
}
return ret;
}
@Override
public int getViewHorizontalDragRange(View child) {
return mEdgeFlag & (EDGE_LEFT | EDGE_RIGHT);
}
@Override
public int getViewVerticalDragRange(View child) {
return mEdgeFlag & EDGE_BOTTOM;
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
super.onViewPositionChanged(changedView, left, top, dx, dy);
if ((mTrackingEdge & EDGE_LEFT) != 0) {
mScrollPercent = Math.abs((float) left
/ (mContentView.getWidth() + mShadowLeft.getIntrinsicWidth()));
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
mScrollPercent = Math.abs((float) left
/ (mContentView.getWidth() + mShadowRight.getIntrinsicWidth()));
} else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
mScrollPercent = Math.abs((float) top
/ (mContentView.getHeight() + mShadowBottom.getIntrinsicHeight()));
}
mContentLeft = left;
mContentTop = top;
invalidate();
if (mScrollPercent < mScrollThreshold && !mIsScrollOverValid) {
mIsScrollOverValid = true;
}
if (mListeners != null && !mListeners.isEmpty()
&& mDragHelper.getViewDragState() == STATE_DRAGGING
&& mScrollPercent >= mScrollThreshold && mIsScrollOverValid) {
mIsScrollOverValid = false;
for (SwipeListener listener : mListeners) {
listener.onScrollOverThreshold();
}
}
if (mScrollPercent >= 1) {
if (!mActivity.isFinishing()) {
mActivity.finish();
mActivity.overridePendingTransition(0, 0);
}
}
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
final int childWidth = releasedChild.getWidth();
final int childHeight = releasedChild.getHeight();
int left = 0, top = 0;
if ((mTrackingEdge & EDGE_LEFT) != 0) {
left = xvel > 0 || xvel == 0 && mScrollPercent > mScrollThreshold ? childWidth
+ mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE : 0;
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
left = xvel < 0 || xvel == 0 && mScrollPercent > mScrollThreshold ? -(childWidth
+ mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE) : 0;
} else if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
top = yvel < 0 || yvel == 0 && mScrollPercent > mScrollThreshold ? -(childHeight
+ mShadowBottom.getIntrinsicHeight() + OVERSCROLL_DISTANCE) : 0;
}
mDragHelper.settleCapturedViewAt(left, top);
invalidate();
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
int ret = 0;
if ((mTrackingEdge & EDGE_LEFT) != 0) {
ret = Math.min(child.getWidth(), Math.max(left, 0));
} else if ((mTrackingEdge & EDGE_RIGHT) != 0) {
ret = Math.min(0, Math.max(left, -child.getWidth()));
}
return ret;
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
int ret = 0;
if ((mTrackingEdge & EDGE_BOTTOM) != 0) {
ret = Math.min(0, Math.max(top, -child.getHeight()));
}
return ret;
}
@Override
public void onViewDragStateChanged(int state) {
super.onViewDragStateChanged(state);
if (mListeners != null && !mListeners.isEmpty()) {
for (SwipeListener listener : mListeners) {
listener.onScrollStateChange(state, mScrollPercent);
}
}
}
}
}
================================================
FILE: hydrogen-library/src/main/java/androlua/widget/swipebacklayout/Utils.java
================================================
package androlua.widget.swipebacklayout;
import android.app.Activity;
import java.lang.reflect.Method;
/**
* Created by Chaojun Wang on 6/9/14.
*/
public class Utils {
private Utils() {
}
/**
* Convert a translucent themed Activity
* {@link android.R.attr#windowIsTranslucent} to a fullscreen opaque
* Activity.
*
* Call this whenever the background of a translucent Activity has changed
* to become opaque. Doing so will allow the {@link android.view.Surface} of
* the Activity behind to be released.
*
* This call has no effect on non-translucent activities or on activities
* with the {@link android.R.attr#windowIsFloating} attribute.
*/
public static void convertActivityFromTranslucent(Activity activity) {
try {
Method method = Activity.class.getDeclaredMethod("convertFromTranslucent");
method.setAccessible(true);
method.invoke(activity);
} catch (Throwable t) {
}
}
/**
* Convert a translucent themed Activity
* {@link android.R.attr#windowIsTranslucent} back from opaque to
* translucent following a call to
* {@link #convertActivityFromTranslucent(Activity)} .
*
* Calling this allows the Activity behind this one to be seen again. Once
* all such Activities have been redrawn
*
* This call has no effect on non-translucent activities or on activities
* with the {@link android.R.attr#windowIsFloating} attribute.
*/
public static void convertActivityToTranslucent(Activity activity) {
try {
Class>[] classes = Activity.class.getDeclaredClasses();
Class> translucentConversionListenerClazz = null;
for (Class clazz : classes) {
if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
translucentConversionListenerClazz = clazz;
}
}
Method method = Activity.class.getDeclaredMethod("convertToTranslucent",
translucentConversionListenerClazz);
method.setAccessible(true);
method.invoke(activity, new Object[]{
null
});
} catch (Throwable t) {
}
}
}
================================================
FILE: hydrogen-library/src/main/java/androlua/widget/swipebacklayout/ViewDragHelper.java
================================================
/*
* 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 androlua.widget.swipebacklayout;
import android.content.Context;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.VelocityTrackerCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ScrollerCompat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import java.util.Arrays;
/**
* ViewDragHelper is a utility class for writing custom ViewGroups. It offers a
* number of useful operations and state tracking for allowing a user to drag
* and reposition views within their parent ViewGroup.
*/
public class ViewDragHelper {
/**
* A null/invalid pointer ID.
*/
public static final int INVALID_POINTER = -1;
/**
* A view is not currently being dragged or animating as a result of a
* fling/snap.
*/
public static final int STATE_IDLE = 0;
/**
* A view is currently being dragged. The position is currently changing as
* a result of user input or simulated user input.
*/
public static final int STATE_DRAGGING = 1;
/**
* A view is currently settling into place as a result of a fling or
* predefined non-interactive motion.
*/
public static final int STATE_SETTLING = 2;
/**
* Edge flag indicating that the left edge should be affected.
*/
public static final int EDGE_LEFT = 1 << 0;
/**
* Edge flag indicating that the right edge should be affected.
*/
public static final int EDGE_RIGHT = 1 << 1;
/**
* Edge flag indicating that the top edge should be affected.
*/
public static final int EDGE_TOP = 1 << 2;
/**
* Edge flag indicating that the bottom edge should be affected.
*/
public static final int EDGE_BOTTOM = 1 << 3;
/**
* Edge flag set indicating all edges should be affected.
*/
public static final int EDGE_ALL = EDGE_LEFT | EDGE_TOP | EDGE_RIGHT | EDGE_BOTTOM;
/**
* Indicates that a check should occur along the horizontal axis
*/
public static final int DIRECTION_HORIZONTAL = 1 << 0;
/**
* Indicates that a check should occur along the vertical axis
*/
public static final int DIRECTION_VERTICAL = 1 << 1;
/**
* Indicates that a check should occur along all axes
*/
public static final int DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
public static final int EDGE_SIZE = 20; // dp
private static final String TAG = "ViewDragHelper";
private static final int BASE_SETTLE_DURATION = 256; // ms
private static final int MAX_SETTLE_DURATION = 600; // ms
/**
* Interpolator defining the animation curve for mScroller
*/
private static final Interpolator sInterpolator = new Interpolator() {
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
private final Callback mCallback;
private final ViewGroup mParentView;
// Current drag state; idle, dragging or settling
private int mDragState;
// Distance to travel before a drag may begin
private int mTouchSlop;
// Last known position/pointer tracking
private int mActivePointerId = INVALID_POINTER;
private float[] mInitialMotionX;
private float[] mInitialMotionY;
private float[] mLastMotionX;
private float[] mLastMotionY;
private int[] mInitialEdgeTouched;
private int[] mEdgeDragsInProgress;
private int[] mEdgeDragsLocked;
private int mPointersDown;
private VelocityTracker mVelocityTracker;
private float mMaxVelocity;
private float mMinVelocity;
private int mEdgeSize;
private int mTrackingEdges;
private ScrollerCompat mScroller;
private View mCapturedView;
private final Runnable mSetIdleRunnable = new Runnable() {
public void run() {
setDragState(STATE_IDLE);
}
};
private boolean mReleaseInProgress;
/**
* Apps should use ViewDragHelper.create() to get a new instance. This will
* allow VDH to use internal compatibility implementations for different
* platform versions.
*
* @param context Context to initialize config-dependent params from
* @param forParent Parent view to monitor
*/
private ViewDragHelper(Context context, ViewGroup forParent, Callback cb) {
if (forParent == null) {
throw new IllegalArgumentException("Parent view may not be null");
}
if (cb == null) {
throw new IllegalArgumentException("Callback may not be null");
}
mParentView = forParent;
mCallback = cb;
final ViewConfiguration vc = ViewConfiguration.get(context);
final float density = context.getResources().getDisplayMetrics().density;
mEdgeSize = (int) (EDGE_SIZE * density + 0.5f);
mTouchSlop = vc.getScaledTouchSlop();
mMaxVelocity = vc.getScaledMaximumFlingVelocity();
mMinVelocity = vc.getScaledMinimumFlingVelocity();
mScroller = ScrollerCompat.create(context, sInterpolator);
}
/**
* Factory method to create a new ViewDragHelper.
*
* @param forParent Parent view to monitor
* @param cb Callback to provide information and receive events
* @return a new ViewDragHelper instance
*/
public static ViewDragHelper create(ViewGroup forParent, Callback cb) {
return new ViewDragHelper(forParent.getContext(), forParent, cb);
}
/**
* Factory method to create a new ViewDragHelper.
*
* @param forParent Parent view to monitor
* @param sensitivity Multiplier for how sensitive the helper should be
* about detecting the start of a drag. Larger values are more
* sensitive. 1.0f is normal.
* @param cb Callback to provide information and receive events
* @return a new ViewDragHelper instance
*/
public static ViewDragHelper create(ViewGroup forParent, float sensitivity, Callback cb) {
final ViewDragHelper helper = create(forParent, cb);
helper.mTouchSlop = (int) (helper.mTouchSlop * (1 / sensitivity));
return helper;
}
/**
* Sets the sensitivity of the dragger.
*
* @param context The application context.
* @param sensitivity value between 0 and 1, the final value for touchSlop =
* ViewConfiguration.getScaledTouchSlop * (1 / s);
*/
public void setSensitivity(Context context, float sensitivity) {
float s = Math.max(0f, Math.min(1.0f, sensitivity));
ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
mTouchSlop = (int) (viewConfiguration.getScaledTouchSlop() * (1 / s));
}
/**
* Set the max velocity that will be detected as having a magnitude
* greater than zero in pixels per second. Callback methods accepting a
* velocity will be clamped appropriately.
*
* @param maxVel max velocity to detect
*/
public void setMaxVelocity(float maxVel) {
mMaxVelocity = maxVel;
}
/**
* Return the currently configured minimum velocity. Any flings with a
* magnitude less than this value in pixels per second. Callback methods
* accepting a velocity will receive zero as a velocity value if the real
* detected velocity was below this threshold.
*
* @return the minimum velocity that will be detected
*/
public float getMinVelocity() {
return mMinVelocity;
}
/**
* Set the minimum velocity that will be detected as having a magnitude
* greater than zero in pixels per second. Callback methods accepting a
* velocity will be clamped appropriately.
*
* @param minVel minimum velocity to detect
*/
public void setMinVelocity(float minVel) {
mMinVelocity = minVel;
}
/**
* Retrieve the current drag state of this helper. This will return one of
* {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}.
*
* @return The current drag state
*/
public int getViewDragState() {
return mDragState;
}
/**
* Enable edge tracking for the selected edges of the parent view. The
* callback's
* {@link ViewDragHelper.Callback#onEdgeTouched(int, int)}
* and
* {@link ViewDragHelper.Callback#onEdgeDragStarted(int, int)}
* methods will only be invoked for edges for which edge tracking has been
* enabled.
*
* @param edgeFlags Combination of edge flags describing the edges to watch
* @see #EDGE_LEFT
* @see #EDGE_TOP
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void setEdgeTrackingEnabled(int edgeFlags) {
mTrackingEdges = edgeFlags;
}
/**
* Return the size of an edge. This is the range in pixels along the edges
* of this view that will actively detect edge touches or drags if edge
* tracking is enabled.
*
* @return The size of an edge in pixels
* @see #setEdgeTrackingEnabled(int)
*/
public int getEdgeSize() {
return mEdgeSize;
}
/**
* Set the size of an edge. This is the range in pixels along the edges of
* this view that will actively detect edge touches or drags if edge
* tracking is enabled.
*
* @param size The size of an edge in pixels
*/
public void setEdgeSize(int size) {
mEdgeSize = size;
}
/**
* Capture a specific child view for dragging within the parent. The
* callback will be notified but
* {@link ViewDragHelper.Callback#tryCaptureView(View, int)}
* will not be asked permission to capture this view.
*
* @param childView Child view to capture
* @param activePointerId ID of the pointer that is dragging the captured
* child view
*/
public void captureChildView(View childView, int activePointerId) {
if (childView.getParent() != mParentView) {
throw new IllegalArgumentException("captureChildView: parameter must be a descendant "
+ "of the ViewDragHelper's tracked parent view (" + mParentView + ")");
}
mCapturedView = childView;
mActivePointerId = activePointerId;
mCallback.onViewCaptured(childView, activePointerId);
setDragState(STATE_DRAGGING);
}
/**
* @return The currently captured view, or null if no view has been
* captured.
*/
public View getCapturedView() {
return mCapturedView;
}
/**
* @return The ID of the pointer currently dragging the captured view, or
* {@link #INVALID_POINTER}.
*/
public int getActivePointerId() {
return mActivePointerId;
}
/**
* @return The minimum distance in pixels that the user must travel to
* initiate a drag
*/
public int getTouchSlop() {
return mTouchSlop;
}
/**
* The result of a call to this method is equivalent to
* {@link #processTouchEvent(MotionEvent)} receiving an
* ACTION_CANCEL event.
*/
public void cancel() {
mActivePointerId = INVALID_POINTER;
clearMotionHistory();
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
/**
* {@link #cancel()}, but also abort all motion in progress and snap to the
* end of any animation.
*/
public void abort() {
cancel();
if (mDragState == STATE_SETTLING) {
final int oldX = mScroller.getCurrX();
final int oldY = mScroller.getCurrY();
mScroller.abortAnimation();
final int newX = mScroller.getCurrX();
final int newY = mScroller.getCurrY();
mCallback.onViewPositionChanged(mCapturedView, newX, newY, newX - oldX, newY - oldY);
}
setDragState(STATE_IDLE);
}
/**
* Animate the view child to the given (left, top) position. If
* this method returns true, the caller should invoke
* {@link #continueSettling(boolean)} on each subsequent frame to continue
* the motion until it returns false. If this method returns false there is
* no further work to do to complete the movement.
*
* This operation does not count as a capture event, though
* {@link #getCapturedView()} will still report the sliding view while the
* slide is in progress.
*
*
* @param child Child view to capture and animate
* @param finalLeft Final left position of child
* @param finalTop Final top position of child
* @return true if animation should continue through
* {@link #continueSettling(boolean)} calls
*/
public boolean smoothSlideViewTo(View child, int finalLeft, int finalTop) {
mCapturedView = child;
mActivePointerId = INVALID_POINTER;
return forceSettleCapturedViewAt(finalLeft, finalTop, 0, 0);
}
/**
* Settle the captured view at the given (left, top) position. The
* appropriate velocity from prior motion will be taken into account. If
* this method returns true, the caller should invoke
* {@link #continueSettling(boolean)} on each subsequent frame to continue
* the motion until it returns false. If this method returns false there is
* no further work to do to complete the movement.
*
* @param finalLeft Settled left edge position for the captured view
* @param finalTop Settled top edge position for the captured view
* @return true if animation should continue through
* {@link #continueSettling(boolean)} calls
*/
public boolean settleCapturedViewAt(int finalLeft, int finalTop) {
if (!mReleaseInProgress) {
throw new IllegalStateException("Cannot settleCapturedViewAt outside of a call to "
+ "Callback#onViewReleased");
}
return forceSettleCapturedViewAt(finalLeft, finalTop,
(int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId),
(int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId));
}
/**
* Settle the captured view at the given (left, top) position.
*
* @param finalLeft Target left position for the captured view
* @param finalTop Target top position for the captured view
* @param xvel Horizontal velocity
* @param yvel Vertical velocity
* @return true if animation should continue through
* {@link #continueSettling(boolean)} calls
*/
private boolean forceSettleCapturedViewAt(int finalLeft, int finalTop, int xvel, int yvel) {
final int startLeft = mCapturedView.getLeft();
final int startTop = mCapturedView.getTop();
final int dx = finalLeft - startLeft;
final int dy = finalTop - startTop;
if (dx == 0 && dy == 0) {
// Nothing to do. Send callbacks, be done.
mScroller.abortAnimation();
setDragState(STATE_IDLE);
return false;
}
final int duration = computeSettleDuration(mCapturedView, dx, dy, xvel, yvel);
mScroller.startScroll(startLeft, startTop, dx, dy, duration);
setDragState(STATE_SETTLING);
return true;
}
private int computeSettleDuration(View child, int dx, int dy, int xvel, int yvel) {
xvel = clampMag(xvel, (int) mMinVelocity, (int) mMaxVelocity);
yvel = clampMag(yvel, (int) mMinVelocity, (int) mMaxVelocity);
final int absDx = Math.abs(dx);
final int absDy = Math.abs(dy);
final int absXVel = Math.abs(xvel);
final int absYVel = Math.abs(yvel);
final int addedVel = absXVel + absYVel;
final int addedDistance = absDx + absDy;
final float xweight = xvel != 0 ? (float) absXVel / addedVel : (float) absDx
/ addedDistance;
final float yweight = yvel != 0 ? (float) absYVel / addedVel : (float) absDy
/ addedDistance;
int xduration = computeAxisDuration(dx, xvel, mCallback.getViewHorizontalDragRange(child));
int yduration = computeAxisDuration(dy, yvel, mCallback.getViewVerticalDragRange(child));
return (int) (xduration * xweight + yduration * yweight);
}
private int computeAxisDuration(int delta, int velocity, int motionRange) {
if (delta == 0) {
return 0;
}
final int width = mParentView.getWidth();
final int halfWidth = width / 2;
final float distanceRatio = Math.min(1f, (float) Math.abs(delta) / width);
final float distance = halfWidth + halfWidth
* distanceInfluenceForSnapDuration(distanceRatio);
int duration;
velocity = Math.abs(velocity);
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
final float range = (float) Math.abs(delta) / motionRange;
duration = (int) ((range + 1) * BASE_SETTLE_DURATION);
}
return Math.min(duration, MAX_SETTLE_DURATION);
}
/**
* Clamp the magnitude of value for absMin and absMax. If the value is below
* the minimum, it will be clamped to zero. If the value is above the
* maximum, it will be clamped to the maximum.
*
* @param value Value to clamp
* @param absMin Absolute value of the minimum significant value to return
* @param absMax Absolute value of the maximum value to return
* @return The clamped value with the same sign as value
*/
private int clampMag(int value, int absMin, int absMax) {
final int absValue = Math.abs(value);
if (absValue < absMin)
return 0;
if (absValue > absMax)
return value > 0 ? absMax : -absMax;
return value;
}
/**
* Clamp the magnitude of value for absMin and absMax. If the value is below
* the minimum, it will be clamped to zero. If the value is above the
* maximum, it will be clamped to the maximum.
*
* @param value Value to clamp
* @param absMin Absolute value of the minimum significant value to return
* @param absMax Absolute value of the maximum value to return
* @return The clamped value with the same sign as value
*/
private float clampMag(float value, float absMin, float absMax) {
final float absValue = Math.abs(value);
if (absValue < absMin)
return 0;
if (absValue > absMax)
return value > 0 ? absMax : -absMax;
return value;
}
private float distanceInfluenceForSnapDuration(float f) {
f -= 0.5f; // center the values about 0.
f *= 0.3f * Math.PI / 2.0f;
return (float) Math.sin(f);
}
/**
* Settle the captured view based on standard free-moving fling behavior.
* The caller should invoke {@link #continueSettling(boolean)} on each
* subsequent frame to continue the motion until it returns false.
*
* @param minLeft Minimum X position for the view's left edge
* @param minTop Minimum Y position for the view's top edge
* @param maxLeft Maximum X position for the view's left edge
* @param maxTop Maximum Y position for the view's top edge
*/
public void flingCapturedView(int minLeft, int minTop, int maxLeft, int maxTop) {
if (!mReleaseInProgress) {
throw new IllegalStateException("Cannot flingCapturedView outside of a call to "
+ "Callback#onViewReleased");
}
mScroller.fling(mCapturedView.getLeft(), mCapturedView.getTop(),
(int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId),
(int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId),
minLeft, maxLeft, minTop, maxTop);
setDragState(STATE_SETTLING);
}
/**
* Move the captured settling view by the appropriate amount for the current
* time. If continueSettling returns true, the caller should
* call it again on the next frame to continue.
*
* @param deferCallbacks true if state callbacks should be deferred via
* posted message. Set this to true if you are calling this
* method from {@link View#computeScroll()} or
* similar methods invoked as part of layout or drawing.
* @return true if settle is still in progress
*/
public boolean continueSettling(boolean deferCallbacks) {
if (mDragState == STATE_SETTLING) {
boolean keepGoing = mScroller.computeScrollOffset();
final int x = mScroller.getCurrX();
final int y = mScroller.getCurrY();
final int dx = x - mCapturedView.getLeft();
final int dy = y - mCapturedView.getTop();
if (dx != 0) {
mCapturedView.offsetLeftAndRight(dx);
}
if (dy != 0) {
mCapturedView.offsetTopAndBottom(dy);
}
if (dx != 0 || dy != 0) {
mCallback.onViewPositionChanged(mCapturedView, x, y, dx, dy);
}
if (keepGoing && x == mScroller.getFinalX() && y == mScroller.getFinalY()) {
// Close enough. The interpolator/scroller might think we're
// still moving
// but the user sure doesn't.
mScroller.abortAnimation();
keepGoing = mScroller.isFinished();
}
if (!keepGoing) {
if (deferCallbacks) {
mParentView.post(mSetIdleRunnable);
} else {
setDragState(STATE_IDLE);
}
}
}
return mDragState == STATE_SETTLING;
}
/**
* Like all callback events this must happen on the UI thread, but release
* involves some extra semantics. During a release (mReleaseInProgress) is
* the only time it is valid to call {@link #settleCapturedViewAt(int, int)}
* or {@link #flingCapturedView(int, int, int, int)}.
*/
private void dispatchViewReleased(float xvel, float yvel) {
mReleaseInProgress = true;
mCallback.onViewReleased(mCapturedView, xvel, yvel);
mReleaseInProgress = false;
if (mDragState == STATE_DRAGGING) {
// onViewReleased didn't call a method that would have changed this.
// Go idle.
setDragState(STATE_IDLE);
}
}
private void clearMotionHistory() {
if (mInitialMotionX == null) {
return;
}
Arrays.fill(mInitialMotionX, 0);
Arrays.fill(mInitialMotionY, 0);
Arrays.fill(mLastMotionX, 0);
Arrays.fill(mLastMotionY, 0);
Arrays.fill(mInitialEdgeTouched, 0);
Arrays.fill(mEdgeDragsInProgress, 0);
Arrays.fill(mEdgeDragsLocked, 0);
mPointersDown = 0;
}
private void clearMotionHistory(int pointerId) {
if (mInitialMotionX == null) {
return;
}
mInitialMotionX[pointerId] = 0;
mInitialMotionY[pointerId] = 0;
mLastMotionX[pointerId] = 0;
mLastMotionY[pointerId] = 0;
mInitialEdgeTouched[pointerId] = 0;
mEdgeDragsInProgress[pointerId] = 0;
mEdgeDragsLocked[pointerId] = 0;
mPointersDown &= ~(1 << pointerId);
}
private void ensureMotionHistorySizeForId(int pointerId) {
if (mInitialMotionX == null || mInitialMotionX.length <= pointerId) {
float[] imx = new float[pointerId + 1];
float[] imy = new float[pointerId + 1];
float[] lmx = new float[pointerId + 1];
float[] lmy = new float[pointerId + 1];
int[] iit = new int[pointerId + 1];
int[] edip = new int[pointerId + 1];
int[] edl = new int[pointerId + 1];
if (mInitialMotionX != null) {
System.arraycopy(mInitialMotionX, 0, imx, 0, mInitialMotionX.length);
System.arraycopy(mInitialMotionY, 0, imy, 0, mInitialMotionY.length);
System.arraycopy(mLastMotionX, 0, lmx, 0, mLastMotionX.length);
System.arraycopy(mLastMotionY, 0, lmy, 0, mLastMotionY.length);
System.arraycopy(mInitialEdgeTouched, 0, iit, 0, mInitialEdgeTouched.length);
System.arraycopy(mEdgeDragsInProgress, 0, edip, 0, mEdgeDragsInProgress.length);
System.arraycopy(mEdgeDragsLocked, 0, edl, 0, mEdgeDragsLocked.length);
}
mInitialMotionX = imx;
mInitialMotionY = imy;
mLastMotionX = lmx;
mLastMotionY = lmy;
mInitialEdgeTouched = iit;
mEdgeDragsInProgress = edip;
mEdgeDragsLocked = edl;
}
}
private void saveInitialMotion(float x, float y, int pointerId) {
ensureMotionHistorySizeForId(pointerId);
mInitialMotionX[pointerId] = mLastMotionX[pointerId] = x;
mInitialMotionY[pointerId] = mLastMotionY[pointerId] = y;
mInitialEdgeTouched[pointerId] = getEdgeTouched((int) x, (int) y);
mPointersDown |= 1 << pointerId;
}
private void saveLastMotion(MotionEvent ev) {
final int pointerCount = MotionEventCompat.getPointerCount(ev);
for (int i = 0; i < pointerCount; i++) {
final int pointerId = MotionEventCompat.getPointerId(ev, i);
final float x = MotionEventCompat.getX(ev, i);
final float y = MotionEventCompat.getY(ev, i);
mLastMotionX[pointerId] = x;
mLastMotionY[pointerId] = y;
}
}
/**
* Check if the given pointer ID represents a pointer that is currently down
* (to the best of the ViewDragHelper's knowledge).
*
* The state used to report this information is populated by the methods
* {@link #shouldInterceptTouchEvent(MotionEvent)} or
* {@link #processTouchEvent(MotionEvent)}. If one of these
* methods has not been called for all relevant MotionEvents to track, the
* information reported by this method may be stale or incorrect.
*
*
* @param pointerId pointer ID to check; corresponds to IDs provided by
* MotionEvent
* @return true if the pointer with the given ID is still down
*/
public boolean isPointerDown(int pointerId) {
return (mPointersDown & 1 << pointerId) != 0;
}
void setDragState(int state) {
if (mDragState != state) {
mDragState = state;
mCallback.onViewDragStateChanged(state);
if (state == STATE_IDLE) {
mCapturedView = null;
}
}
}
/**
* Attempt to capture the view with the given pointer ID. The callback will
* be involved. This will put us into the "dragging" state. If we've already
* captured this view with this pointer this method will immediately return
* true without consulting the callback.
*
* @param toCapture View to capture
* @param pointerId Pointer to capture with
* @return true if capture was successful
*/
boolean tryCaptureViewForDrag(View toCapture, int pointerId) {
if (toCapture == mCapturedView && mActivePointerId == pointerId) {
// Already done!
return true;
}
if (toCapture != null && mCallback.tryCaptureView(toCapture, pointerId)) {
mActivePointerId = pointerId;
captureChildView(toCapture, pointerId);
return true;
}
return false;
}
/**
* Tests scrollability within child views of v given a delta of dx.
*
* @param v View to test for horizontal scrollability
* @param checkV Whether the view v passed should itself be checked for
* scrollability (true), or just its children (false).
* @param dx Delta scrolled in pixels along the X axis
* @param dy Delta scrolled in pixels along the Y axis
* @param x X coordinate of the active touch point
* @param y Y coordinate of the active touch point
* @return true if child views of v can be scrolled by delta of dx.
*/
protected boolean canScroll(View v, boolean checkV, int dx, int dy, int x, int y) {
if (v instanceof ViewGroup) {
final ViewGroup group = (ViewGroup) v;
final int scrollX = v.getScrollX();
final int scrollY = v.getScrollY();
final int count = group.getChildCount();
// Count backwards - let topmost views consume scroll distance
// first.
for (int i = count - 1; i >= 0; i--) {
// TODO: Add versioned support here for transformed views.
// This will not work for transformed views in Honeycomb+
final View child = group.getChildAt(i);
if (x + scrollX >= child.getLeft()
&& x + scrollX < child.getRight()
&& y + scrollY >= child.getTop()
&& y + scrollY < child.getBottom()
&& canScroll(child, true, dx, dy, x + scrollX - child.getLeft(), y
+ scrollY - child.getTop())) {
return true;
}
}
}
return checkV
&& (ViewCompat.canScrollHorizontally(v, -dx) || ViewCompat.canScrollVertically(v,
-dy));
}
/**
* Check if this event as provided to the parent view's
* onInterceptTouchEvent should cause the parent to intercept the touch
* event stream.
*
* @param ev MotionEvent provided to onInterceptTouchEvent
* @return true if the parent view should return true from
* onInterceptTouchEvent
*/
public boolean shouldInterceptTouchEvent(MotionEvent ev) {
final int action = MotionEventCompat.getActionMasked(ev);
final int actionIndex = MotionEventCompat.getActionIndex(ev);
if (action == MotionEvent.ACTION_DOWN) {
// Reset things for a new event stream, just in case we didn't get
// the whole previous stream.
cancel();
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
switch (action) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
final int pointerId = MotionEventCompat.getPointerId(ev, 0);
saveInitialMotion(x, y, pointerId);
final View toCapture = findTopChildUnder((int) x, (int) y);
// Catch a settling view if possible.
if (toCapture == mCapturedView && mDragState == STATE_SETTLING) {
tryCaptureViewForDrag(toCapture, pointerId);
}
final int edgesTouched = mInitialEdgeTouched[pointerId];
if ((edgesTouched & mTrackingEdges) != 0) {
mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
}
break;
}
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
final float x = MotionEventCompat.getX(ev, actionIndex);
final float y = MotionEventCompat.getY(ev, actionIndex);
saveInitialMotion(x, y, pointerId);
// A ViewDragHelper can only manipulate one view at a time.
if (mDragState == STATE_IDLE) {
final int edgesTouched = mInitialEdgeTouched[pointerId];
if ((edgesTouched & mTrackingEdges) != 0) {
mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
}
} else if (mDragState == STATE_SETTLING) {
// Catch a settling view if possible.
final View toCapture = findTopChildUnder((int) x, (int) y);
if (toCapture == mCapturedView) {
tryCaptureViewForDrag(toCapture, pointerId);
}
}
break;
}
case MotionEvent.ACTION_MOVE: {
// First to cross a touch slop over a draggable view wins. Also
// report edge drags.
final int pointerCount = MotionEventCompat.getPointerCount(ev);
for (int i = 0; i < pointerCount; i++) {
final int pointerId = MotionEventCompat.getPointerId(ev, i);
final float x = MotionEventCompat.getX(ev, i);
final float y = MotionEventCompat.getY(ev, i);
final float dx = x - mInitialMotionX[pointerId];
final float dy = y - mInitialMotionY[pointerId];
reportNewEdgeDrags(dx, dy, pointerId);
if (mDragState == STATE_DRAGGING) {
// Callback might have started an edge drag
break;
}
final View toCapture = findTopChildUnder((int) x, (int) y);
if (toCapture != null && checkTouchSlop(toCapture, dx, dy)
&& tryCaptureViewForDrag(toCapture, pointerId)) {
break;
}
}
saveLastMotion(ev);
break;
}
case MotionEventCompat.ACTION_POINTER_UP: {
final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
clearMotionHistory(pointerId);
break;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
cancel();
break;
}
}
return mDragState == STATE_DRAGGING;
}
/**
* Process a touch event received by the parent view. This method will
* dispatch callback events as needed before returning. The parent view's
* onTouchEvent implementation should call this.
*
* @param ev The touch event received by the parent view
*/
public void processTouchEvent(MotionEvent ev) {
final int action = MotionEventCompat.getActionMasked(ev);
final int actionIndex = MotionEventCompat.getActionIndex(ev);
if (action == MotionEvent.ACTION_DOWN) {
// Reset things for a new event stream, just in case we didn't get
// the whole previous stream.
cancel();
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
switch (action) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
final int pointerId = MotionEventCompat.getPointerId(ev, 0);
final View toCapture = findTopChildUnder((int) x, (int) y);
saveInitialMotion(x, y, pointerId);
// Since the parent is already directly processing this touch
// event,
// there is no reason to delay for a slop before dragging.
// Start immediately if possible.
tryCaptureViewForDrag(toCapture, pointerId);
final int edgesTouched = mInitialEdgeTouched[pointerId];
if ((edgesTouched & mTrackingEdges) != 0) {
mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
}
break;
}
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
final float x = MotionEventCompat.getX(ev, actionIndex);
final float y = MotionEventCompat.getY(ev, actionIndex);
saveInitialMotion(x, y, pointerId);
// A ViewDragHelper can only manipulate one view at a time.
if (mDragState == STATE_IDLE) {
// If we're idle we can do anything! Treat it like a normal
// down event.
final View toCapture = findTopChildUnder((int) x, (int) y);
tryCaptureViewForDrag(toCapture, pointerId);
final int edgesTouched = mInitialEdgeTouched[pointerId];
if ((edgesTouched & mTrackingEdges) != 0) {
mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
}
} else if (isCapturedViewUnder((int) x, (int) y)) {
// We're still tracking a captured view. If the same view is
// under this
// point, we'll swap to controlling it with this pointer
// instead.
// (This will still work if we're "catching" a settling
// view.)
tryCaptureViewForDrag(mCapturedView, pointerId);
}
break;
}
case MotionEvent.ACTION_MOVE: {
if (mDragState == STATE_DRAGGING) {
final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (index == -1) {
Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent");
break;
}
final float x = MotionEventCompat.getX(ev, index);
final float y = MotionEventCompat.getY(ev, index);
final int idx = (int) (x - mLastMotionX[mActivePointerId]);
final int idy = (int) (y - mLastMotionY[mActivePointerId]);
dragTo(mCapturedView.getLeft() + idx, mCapturedView.getTop() + idy, idx, idy);
saveLastMotion(ev);
} else {
// Check to see if any pointer is now over a draggable view.
final int pointerCount = MotionEventCompat.getPointerCount(ev);
for (int i = 0; i < pointerCount; i++) {
final int pointerId = MotionEventCompat.getPointerId(ev, i);
final float x = MotionEventCompat.getX(ev, i);
final float y = MotionEventCompat.getY(ev, i);
final float dx = x - mInitialMotionX[pointerId];
final float dy = y - mInitialMotionY[pointerId];
reportNewEdgeDrags(dx, dy, pointerId);
if (mDragState == STATE_DRAGGING) {
// Callback might have started an edge drag.
break;
}
final View toCapture = findTopChildUnder((int) x, (int) y);
if (checkTouchSlop(toCapture, dx, dy)
&& tryCaptureViewForDrag(toCapture, pointerId)) {
break;
}
}
saveLastMotion(ev);
}
break;
}
case MotionEventCompat.ACTION_POINTER_UP: {
final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
if (mDragState == STATE_DRAGGING && pointerId == mActivePointerId) {
// Try to find another pointer that's still holding on to
// the captured view.
int newActivePointer = INVALID_POINTER;
final int pointerCount = MotionEventCompat.getPointerCount(ev);
for (int i = 0; i < pointerCount; i++) {
final int id = MotionEventCompat.getPointerId(ev, i);
if (id == mActivePointerId) {
// This one's going away, skipActivity.
continue;
}
final float x = MotionEventCompat.getX(ev, i);
final float y = MotionEventCompat.getY(ev, i);
if (findTopChildUnder((int) x, (int) y) == mCapturedView
&& tryCaptureViewForDrag(mCapturedView, id)) {
newActivePointer = mActivePointerId;
break;
}
}
if (newActivePointer == INVALID_POINTER) {
// We didn't find another pointer still touching the
// view, release it.
releaseViewForPointerUp();
}
}
clearMotionHistory(pointerId);
break;
}
case MotionEvent.ACTION_UP: {
if (mDragState == STATE_DRAGGING) {
releaseViewForPointerUp();
}
cancel();
break;
}
case MotionEvent.ACTION_CANCEL: {
if (mDragState == STATE_DRAGGING) {
dispatchViewReleased(0, 0);
}
cancel();
break;
}
}
}
private void reportNewEdgeDrags(float dx, float dy, int pointerId) {
int dragsStarted = 0;
if (checkNewEdgeDrag(dx, dy, pointerId, EDGE_LEFT)) {
dragsStarted |= EDGE_LEFT;
}
if (checkNewEdgeDrag(dy, dx, pointerId, EDGE_TOP)) {
dragsStarted |= EDGE_TOP;
}
if (checkNewEdgeDrag(dx, dy, pointerId, EDGE_RIGHT)) {
dragsStarted |= EDGE_RIGHT;
}
if (checkNewEdgeDrag(dy, dx, pointerId, EDGE_BOTTOM)) {
dragsStarted |= EDGE_BOTTOM;
}
if (dragsStarted != 0) {
mEdgeDragsInProgress[pointerId] |= dragsStarted;
mCallback.onEdgeDragStarted(dragsStarted, pointerId);
}
}
private boolean checkNewEdgeDrag(float delta, float odelta, int pointerId, int edge) {
final float absDelta = Math.abs(delta);
final float absODelta = Math.abs(odelta);
if ((mInitialEdgeTouched[pointerId] & edge) != edge || (mTrackingEdges & edge) == 0
|| (mEdgeDragsLocked[pointerId] & edge) == edge
|| (mEdgeDragsInProgress[pointerId] & edge) == edge
|| (absDelta <= mTouchSlop && absODelta <= mTouchSlop)) {
return false;
}
if (absDelta < absODelta * 0.5f && mCallback.onEdgeLock(edge)) {
mEdgeDragsLocked[pointerId] |= edge;
return false;
}
return (mEdgeDragsInProgress[pointerId] & edge) == 0 && absDelta > mTouchSlop;
}
/**
* Check if we've crossed a reasonable touch slop for the given child view.
* If the child cannot be dragged along the horizontal or vertical axis,
* motion along that axis will not count toward the slop check.
*
* @param child Child to check
* @param dx Motion since initial position along X axis
* @param dy Motion since initial position along Y axis
* @return true if the touch slop has been crossed
*/
private boolean checkTouchSlop(View child, float dx, float dy) {
if (child == null) {
return false;
}
final boolean checkHorizontal = mCallback.getViewHorizontalDragRange(child) > 0;
final boolean checkVertical = mCallback.getViewVerticalDragRange(child) > 0;
if (checkHorizontal && checkVertical) {
return dx * dx + dy * dy > mTouchSlop * mTouchSlop;
} else if (checkHorizontal) {
return Math.abs(dx) > mTouchSlop;
} else if (checkVertical) {
return Math.abs(dy) > mTouchSlop;
}
return false;
}
/**
* Check if any pointer tracked in the current gesture has crossed the
* required slop threshold.
*
* This depends on internal state populated by
* {@link #shouldInterceptTouchEvent(MotionEvent)} or
* {@link #processTouchEvent(MotionEvent)}. You should only
* rely on the results of this method after all currently available touch
* data has been provided to one of these two methods.
*
*
* @param directions Combination of direction flags, see
* {@link #DIRECTION_HORIZONTAL}, {@link #DIRECTION_VERTICAL},
* {@link #DIRECTION_ALL}
* @return true if the slop threshold has been crossed, false otherwise
*/
public boolean checkTouchSlop(int directions) {
final int count = mInitialMotionX.length;
for (int i = 0; i < count; i++) {
if (checkTouchSlop(directions, i)) {
return true;
}
}
return false;
}
/**
* Check if the specified pointer tracked in the current gesture has crossed
* the required slop threshold.
*
* This depends on internal state populated by
* {@link #shouldInterceptTouchEvent(MotionEvent)} or
* {@link #processTouchEvent(MotionEvent)}. You should only
* rely on the results of this method after all currently available touch
* data has been provided to one of these two methods.
*
*
* @param directions Combination of direction flags, see
* {@link #DIRECTION_HORIZONTAL}, {@link #DIRECTION_VERTICAL},
* {@link #DIRECTION_ALL}
* @param pointerId ID of the pointer to slop check as specified by
* MotionEvent
* @return true if the slop threshold has been crossed, false otherwise
*/
public boolean checkTouchSlop(int directions, int pointerId) {
if (!isPointerDown(pointerId)) {
return false;
}
final boolean checkHorizontal = (directions & DIRECTION_HORIZONTAL) == DIRECTION_HORIZONTAL;
final boolean checkVertical = (directions & DIRECTION_VERTICAL) == DIRECTION_VERTICAL;
final float dx = mLastMotionX[pointerId] - mInitialMotionX[pointerId];
final float dy = mLastMotionY[pointerId] - mInitialMotionY[pointerId];
if (checkHorizontal && checkVertical) {
return dx * dx + dy * dy > mTouchSlop * mTouchSlop;
} else if (checkHorizontal) {
return Math.abs(dx) > mTouchSlop;
} else if (checkVertical) {
return Math.abs(dy) > mTouchSlop;
}
return false;
}
/**
* Check if any of the edges specified were initially touched in the
* currently active gesture. If there is no currently active gesture this
* method will return false.
*
* @param edges Edges to check for an initial edge touch. See
* {@link #EDGE_LEFT}, {@link #EDGE_TOP}, {@link #EDGE_RIGHT},
* {@link #EDGE_BOTTOM} and {@link #EDGE_ALL}
* @return true if any of the edges specified were initially touched in the
* current gesture
*/
public boolean isEdgeTouched(int edges) {
final int count = mInitialEdgeTouched.length;
for (int i = 0; i < count; i++) {
if (isEdgeTouched(edges, i)) {
return true;
}
}
return false;
}
/**
* Check if any of the edges specified were initially touched by the pointer
* with the specified ID. If there is no currently active gesture or if
* there is no pointer with the given ID currently down this method will
* return false.
*
* @param edges Edges to check for an initial edge touch. See
* {@link #EDGE_LEFT}, {@link #EDGE_TOP}, {@link #EDGE_RIGHT},
* {@link #EDGE_BOTTOM} and {@link #EDGE_ALL}
* @return true if any of the edges specified were initially touched in the
* current gesture
*/
public boolean isEdgeTouched(int edges, int pointerId) {
return isPointerDown(pointerId) && (mInitialEdgeTouched[pointerId] & edges) != 0;
}
private void releaseViewForPointerUp() {
mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity);
final float xvel = clampMag(
VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId),
mMinVelocity, mMaxVelocity);
final float yvel = clampMag(
VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId),
mMinVelocity, mMaxVelocity);
dispatchViewReleased(xvel, yvel);
}
private void dragTo(int left, int top, int dx, int dy) {
int clampedX = left;
int clampedY = top;
final int oldLeft = mCapturedView.getLeft();
final int oldTop = mCapturedView.getTop();
if (dx != 0) {
clampedX = mCallback.clampViewPositionHorizontal(mCapturedView, left, dx);
mCapturedView.offsetLeftAndRight(clampedX - oldLeft);
}
if (dy != 0) {
clampedY = mCallback.clampViewPositionVertical(mCapturedView, top, dy);
mCapturedView.offsetTopAndBottom(clampedY - oldTop);
}
if (dx != 0 || dy != 0) {
final int clampedDx = clampedX - oldLeft;
final int clampedDy = clampedY - oldTop;
mCallback
.onViewPositionChanged(mCapturedView, clampedX, clampedY, clampedDx, clampedDy);
}
}
/**
* Determine if the currently captured view is under the given point in the
* parent view's coordinate system. If there is no captured view this method
* will return false.
*
* @param x X position to test in the parent's coordinate system
* @param y Y position to test in the parent's coordinate system
* @return true if the captured view is under the given point, false
* otherwise
*/
public boolean isCapturedViewUnder(int x, int y) {
return isViewUnder(mCapturedView, x, y);
}
/**
* Determine if the supplied view is under the given point in the parent
* view's coordinate system.
*
* @param view Child view of the parent to hit test
* @param x X position to test in the parent's coordinate system
* @param y Y position to test in the parent's coordinate system
* @return true if the supplied view is under the given point, false
* otherwise
*/
public boolean isViewUnder(View view, int x, int y) {
if (view == null) {
return false;
}
return x >= view.getLeft() && x < view.getRight() && y >= view.getTop()
&& y < view.getBottom();
}
/**
* Find the topmost child under the given point within the parent view's
* coordinate system. The child order is determined using
* {@link ViewDragHelper.Callback#getOrderedChildIndex(int)}
* .
*
* @param x X position to test in the parent's coordinate system
* @param y Y position to test in the parent's coordinate system
* @return The topmost child view under (x, y) or null if none found.
*/
public View findTopChildUnder(int x, int y) {
final int childCount = mParentView.getChildCount();
for (int i = childCount - 1; i >= 0; i--) {
final View child = mParentView.getChildAt(mCallback.getOrderedChildIndex(i));
if (x >= child.getLeft() && x < child.getRight() && y >= child.getTop()
&& y < child.getBottom()) {
return child;
}
}
return null;
}
private int getEdgeTouched(int x, int y) {
int result = 0;
if (x < mParentView.getLeft() + mEdgeSize)
result = EDGE_LEFT;
if (y < mParentView.getTop() + mEdgeSize)
result = EDGE_TOP;
if (x > mParentView.getRight() - mEdgeSize)
result = EDGE_RIGHT;
if (y > mParentView.getBottom() - mEdgeSize)
result = EDGE_BOTTOM;
return result;
}
/**
* A Callback is used as a communication channel with the ViewDragHelper
* back to the parent view using it. on*methods are invoked on
* siginficant events and several accessor methods are expected to provide
* the ViewDragHelper with more information about the state of the parent
* view upon request. The callback also makes decisions governing the range
* and draggability of child views.
*/
public static abstract class Callback {
/**
* Called when the drag state changes. See the STATE_*
* constants for more information.
*
* @param state The new drag state
* @see #STATE_IDLE
* @see #STATE_DRAGGING
* @see #STATE_SETTLING
*/
public void onViewDragStateChanged(int state) {
}
/**
* Called when the captured view's position changes as the result of a
* drag or settle.
*
* @param changedView View whose position changed
* @param left New X coordinate of the left edge of the view
* @param top New Y coordinate of the top edge of the view
* @param dx Change in X position from the last call
* @param dy Change in Y position from the last call
*/
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
}
/**
* Called when a child view is captured for dragging or settling. The ID
* of the pointer currently dragging the captured view is supplied. If
* activePointerId is identified as {@link #INVALID_POINTER} the capture
* is programmatic instead of pointer-initiated.
*
* @param capturedChild Child view that was captured
* @param activePointerId Pointer id tracking the child capture
*/
public void onViewCaptured(View capturedChild, int activePointerId) {
}
/**
* Called when the child view is no longer being actively dragged. The
* fling velocity is also supplied, if relevant. The velocity values may
* be clamped to system minimums or maximums.
*
* Calling code may decide to fling or otherwise release the view to let
* it settle into place. It should do so using
* {@link #settleCapturedViewAt(int, int)} or
* {@link #flingCapturedView(int, int, int, int)}. If the Callback
* invokes one of these methods, the ViewDragHelper will enter
* {@link #STATE_SETTLING} and the view capture will not fully end until
* it comes to a complete stop. If neither of these methods is invoked
* before onViewReleased returns, the view will stop in
* place and the ViewDragHelper will return to {@link #STATE_IDLE}.
*
*
* @param releasedChild The captured child view now being released
* @param xvel X velocity of the pointer as it left the screen in pixels
* per second.
* @param yvel Y velocity of the pointer as it left the screen in pixels
* per second.
*/
public void onViewReleased(View releasedChild, float xvel, float yvel) {
}
/**
* Called when one of the subscribed edges in the parent view has been
* touched by the user while no child view is currently captured.
*
* @param edgeFlags A combination of edge flags describing the edge(s)
* currently touched
* @param pointerId ID of the pointer touching the described edge(s)
* @see #EDGE_LEFT
* @see #EDGE_TOP
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void onEdgeTouched(int edgeFlags, int pointerId) {
}
/**
* Called when the given edge may become locked. This can happen if an
* edge drag was preliminarily rejected before beginning, but after
* {@link #onEdgeTouched(int, int)} was called. This method should
* return true to lock this edge or false to leave it unlocked. The
* default behavior is to leave edges unlocked.
*
* @param edgeFlags A combination of edge flags describing the edge(s)
* locked
* @return true to lock the edge, false to leave it unlocked
*/
public boolean onEdgeLock(int edgeFlags) {
return false;
}
/**
* Called when the user has started a deliberate drag away from one of
* the subscribed edges in the parent view while no child view is
* currently captured.
*
* @param edgeFlags A combination of edge flags describing the edge(s)
* dragged
* @param pointerId ID of the pointer touching the described edge(s)
* @see #EDGE_LEFT
* @see #EDGE_TOP
* @see #EDGE_RIGHT
* @see #EDGE_BOTTOM
*/
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
}
/**
* Called to determine the Z-order of child views.
*
* @param index the ordered position to query for
* @return index of the view that should be ordered at position
* index
*/
public int getOrderedChildIndex(int index) {
return index;
}
/**
* Return the magnitude of a draggable child view's horizontal range of
* motion in pixels. This method should return 0 for views that cannot
* move horizontally.
*
* @param child Child view to check
* @return range of horizontal motion in pixels
*/
public int getViewHorizontalDragRange(View child) {
return 0;
}
/**
* Return the magnitude of a draggable child view's vertical range of
* motion in pixels. This method should return 0 for views that cannot
* move vertically.
*
* @param child Child view to check
* @return range of vertical motion in pixels
*/
public int getViewVerticalDragRange(View child) {
return 0;
}
/**
* Called when the user's input indicates that they want to capture the
* given child view with the pointer indicated by pointerId. The
* callback should return true if the user is permitted to drag the
* given view with the indicated pointer.
*
* ViewDragHelper may call this method multiple times for the same view
* even if the view is already captured; this indicates that a new
* pointer is trying to take control of the view.
*
*
* If this method returns true, a call to
* {@link #onViewCaptured(View, int)} will follow if the
* capture is successful.
*
*
* @param child Child the user is attempting to capture
* @param pointerId ID of the pointer attempting the capture
* @return true if capture should be allowed, false otherwise
*/
public abstract boolean tryCaptureView(View child, int pointerId);
/**
* Restrict the motion of the dragged child view along the horizontal
* axis. The default implementation does not allow horizontal motion;
* the extending class must override this method and provide the desired
* clamping.
*
* @param child Child view being dragged
* @param left Attempted motion along the X axis
* @param dx Proposed change in position for left
* @return The new clamped position for left
*/
public int clampViewPositionHorizontal(View child, int left, int dx) {
return 0;
}
/**
* Restrict the motion of the dragged child view along the vertical
* axis. The default implementation does not allow vertical motion; the
* extending class must override this method and provide the desired
* clamping.
*
* @param child Child view being dragged
* @param top Attempted motion along the Y axis
* @param dy Proposed change in position for top
* @return The new clamped position for top
*/
public int clampViewPositionVertical(View child, int top, int dy) {
return 0;
}
}
}
================================================
FILE: hydrogen-library/src/main/java/androlua/widget/swipebacklayout/app/SwipeBackActivity.java
================================================
package androlua.widget.swipebacklayout.app;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import androlua.widget.swipebacklayout.SwipeBackLayout;
import androlua.widget.swipebacklayout.Utils;
public class SwipeBackActivity extends AppCompatActivity implements SwipeBackActivityBase {
private SwipeBackActivityHelper mHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHelper = new SwipeBackActivityHelper(this);
mHelper.onActivityCreate();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if (needPostCreate()) {
mHelper.onPostCreate();
}
}
@Override
public View findViewById(int id) {
View v = super.findViewById(id);
if (v == null && mHelper != null)
return mHelper.findViewById(id);
return v;
}
@Override
public SwipeBackLayout getSwipeBackLayout() {
return mHelper.getSwipeBackLayout();
}
@Override
public void setSwipeBackEnable(boolean enable) {
getSwipeBackLayout().setEnableGesture(enable);
}
@Override
public void scrollToFinishActivity() {
Utils.convertActivityToTranslucent(this);
getSwipeBackLayout().scrollToFinishActivity();
}
protected boolean needPostCreate() {
return true;
}
}
================================================
FILE: hydrogen-library/src/main/java/androlua/widget/swipebacklayout/app/SwipeBackActivityBase.java
================================================
package androlua.widget.swipebacklayout.app;
import androlua.widget.swipebacklayout.SwipeBackLayout;
/**
* @author Yrom
*/
public interface SwipeBackActivityBase {
/**
* @return the SwipeBackLayout associated with this activity.
*/
public abstract SwipeBackLayout getSwipeBackLayout();
public abstract void setSwipeBackEnable(boolean enable);
/**
* Scroll out contentView and finish the activity
*/
public abstract void scrollToFinishActivity();
}
================================================
FILE: hydrogen-library/src/main/java/androlua/widget/swipebacklayout/app/SwipeBackActivityHelper.java
================================================
package androlua.widget.swipebacklayout.app;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.view.ViewGroup;
import androlua.widget.swipebacklayout.SwipeBackLayout;
import androlua.widget.swipebacklayout.Utils;
/**
* @author Yrom
*/
public class SwipeBackActivityHelper {
private Activity mActivity;
private SwipeBackLayout mSwipeBackLayout;
public SwipeBackActivityHelper(Activity activity) {
mActivity = activity;
}
@SuppressWarnings("deprecation")
public void onActivityCreate() {
mActivity.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
mActivity.getWindow().getDecorView().setBackgroundDrawable(null);
mSwipeBackLayout = new SwipeBackLayout(mActivity);
mSwipeBackLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
mSwipeBackLayout.addSwipeListener(new SwipeBackLayout.SwipeListener() {
@Override
public void onScrollStateChange(int state, float scrollPercent) {
}
@Override
public void onEdgeTouch(int edgeFlag) {
Utils.convertActivityToTranslucent(mActivity);
}
@Override
public void onScrollOverThreshold() {
}
});
}
public void onPostCreate() {
mSwipeBackLayout.attachToActivity(mActivity);
}
public View findViewById(int id) {
if (mSwipeBackLayout != null) {
return mSwipeBackLayout.findViewById(id);
}
return null;
}
public SwipeBackLayout getSwipeBackLayout() {
return mSwipeBackLayout;
}
}
================================================
FILE: hydrogen-library/src/main/java/androlua/widget/swipebacklayout/app/SwipeBackPreferenceActivity.java
================================================
package androlua.widget.swipebacklayout.app;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.View;
import androlua.widget.swipebacklayout.SwipeBackLayout;
public class SwipeBackPreferenceActivity extends PreferenceActivity implements SwipeBackActivityBase {
private SwipeBackActivityHelper mHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHelper = new SwipeBackActivityHelper(this);
mHelper.onActivityCreate();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mHelper.onPostCreate();
}
@Override
public View findViewById(int id) {
View v = super.findViewById(id);
if (v == null && mHelper != null)
return mHelper.findViewById(id);
return v;
}
@Override
public SwipeBackLayout getSwipeBackLayout() {
return mHelper.getSwipeBackLayout();
}
@Override
public void setSwipeBackEnable(boolean enable) {
getSwipeBackLayout().setEnableGesture(enable);
}
@Override
public void scrollToFinishActivity() {
getSwipeBackLayout().scrollToFinishActivity();
}
}
================================================
FILE: hydrogen-library/src/main/java/androlua/widget/video/VideoPlayerActivity.java
================================================
package androlua.widget.video;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import org.json.JSONException;
import org.json.JSONObject;
import androlua.LuaImageLoader;
import androlua.base.BaseActivity;
import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;
import pub.hanks.luajandroid.R;
/**
* Created by hanks on 2017/6/2. Copyright (C) 2017 Hanks
*/
public class VideoPlayerActivity extends BaseActivity {
public static void start(Context context, String json) {
Intent starter = new Intent(context, VideoPlayerActivity.class);
starter.putExtra("json", json);
context.startActivity(starter);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
this.getWindow().getDecorView().setBackgroundColor(Color.TRANSPARENT);
JZVideoPlayerStandard videoplayer = (JZVideoPlayerStandard) findViewById(R.id.videoplayer);
try {
String extra = getIntent().getStringExtra("json");
JSONObject json = new JSONObject(extra);
String url = json.getString("url");
String poster = "";
if (json.has("poster")) {
poster = json.getString("poster");
}
LuaImageLoader.load(videoplayer.thumbImageView, poster);
videoplayer.setAllControlsVisiblity(0, 0, 0, 0, 0, View.INVISIBLE, View.INVISIBLE);
videoplayer.setUp(url, JZVideoPlayer.SCREEN_WINDOW_LIST, "");
// JZVideoPlayerStandard.startFullscreen(this, JZVideoPlayerStandard.class, url, "");
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onBackPressed() {
if (JZVideoPlayer.backPress()) {
return;
}
super.onBackPressed();
}
@Override
protected void onPause() {
super.onPause();
JZVideoPlayer.releaseAllVideos();
}
}
================================================
FILE: hydrogen-library/src/main/java/androlua/widget/viewpager/NoScrollViewPager.java
================================================
package androlua.widget.viewpager;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* 可以禁止左右滑动
* Created by hanks on 16/7/18.
*/
public class NoScrollViewPager extends ViewPager {
private boolean isPagingEnabled = false;
public NoScrollViewPager(Context context) {
super(context);
}
public NoScrollViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return this.isPagingEnabled && super.onTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return this.isPagingEnabled && super.onInterceptTouchEvent(event);
}
@Override
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v != this && v instanceof ViewPager) {
int currentItem = ((ViewPager) v).getCurrentItem();
int countItem = ((ViewPager) v).getAdapter().getCount();
return !((currentItem == (countItem - 1) && dx < 0) || (currentItem == 0 && dx > 0));
}
return super.canScroll(v, checkV, dx, x, y);
}
public void setPagingEnabled(boolean b) {
this.isPagingEnabled = b;
}
}
================================================
FILE: hydrogen-library/src/main/java/androlua/widget/webview/WebViewActivity.java
================================================
package androlua.widget.webview;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v4.view.GravityCompat;
import android.support.v7.widget.PopupMenu;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import androlua.LuaUtil;
import androlua.base.BaseActivity;
import androlua.widget.statusbar.StatusBarView;
import pub.hanks.luajandroid.R;
/**
* Created by hanks on 2017/6/2. Copyright (C) 2017 Hanks
*/
public class WebViewActivity extends BaseActivity {
private EditText etUrl;
private String url, webTitle;
private int color;
private WebView mWebView;
private View loading;
private View layout_toolbar;
private View ivRefresh, iv_more;
private Bitmap colorBitmap;
private Canvas canvas;
private StatusBarView view_statusbar;
public static void start(Context context, String url) {
start(context, url, Color.TRANSPARENT);
}
public static void start(Context context, String url, int color) {
Intent starter = new Intent(context, WebViewActivity.class);
starter.putExtra("url", url);
starter.putExtra("color", color);
context.startActivity(starter);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
etUrl = (EditText) findViewById(R.id.et_url);
loading = findViewById(R.id.loading);
layout_toolbar = findViewById(R.id.layout_toolbar);
mWebView = (WebView) findViewById(R.id.webview);
ivRefresh = findViewById(R.id.iv_refresh);
iv_more = findViewById(R.id.iv_more);
view_statusbar = (StatusBarView) findViewById(R.id.view_statusbar);
colorBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565);
canvas = new Canvas(colorBitmap);
WebSettings settings = mWebView.getSettings();
settings.setUseWideViewPort(true);
settings.setAppCacheEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setDisplayZoomControls(false);
settings.setSupportMultipleWindows(true);
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setAllowContentAccess(true);
settings.setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT >= 19) {
mWebView.setWebContentsDebuggingEnabled(true);
}
url = getIntent().getStringExtra("url");
color = getIntent().getIntExtra("color", 0);
if (color == Color.TRANSPARENT) {
setLightStatusBar();
} else {
setStatusBarColor(color);
layout_toolbar.setBackgroundColor(color);
}
etUrl.setText(url);
etUrl.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (TextUtils.isEmpty(url) || TextUtils.isEmpty(webTitle)) {
return;
}
if (hasFocus) {
etUrl.setText(url);
} else {
etUrl.setText(webTitle);
}
}
});
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
webTitle = title;
etUrl.setText(title);
}
});
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loading.setVisibility(View.VISIBLE);
ivRefresh.setVisibility(View.GONE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
loading.setVisibility(View.GONE);
ivRefresh.setVisibility(View.VISIBLE);
fetchColor();
}
@Deprecated
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return !url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("hydrogen://");
}
@Override
public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
String url = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
url = webResourceRequest.getUrl().toString();
}
return !url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("hydrogen://");
}
});
ivRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mWebView.loadUrl(url);
}
});
mWebView.loadUrl(url);
iv_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(iv_more.getContext(), v, GravityCompat.START);
popupMenu.getMenu().add(Menu.NONE, 1, Menu.NONE, "复制链接");
popupMenu.getMenu().add(Menu.NONE, 2, Menu.NONE, "在浏览器打开");
popupMenu.getMenu().add(Menu.NONE, 3, Menu.NONE, "分享");
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (TextUtils.isEmpty(url)) {
return false;
}
switch (item.getItemId()) {
case 1:
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) WebViewActivity.this.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("lua", url);
clipboard.setPrimaryClip(clip);
break;
case 2:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
WebViewActivity.this.startActivity(intent);
break;
case 3:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, url);
sendIntent.setType("text/plain");
WebViewActivity.this.startActivity(sendIntent);
break;
}
return false;
}
});
popupMenu.show();
}
});
etUrl.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
String url = etUrl.getText().toString();
if (!TextUtils.isEmpty(url) && url.startsWith("http")) {
mWebView.loadUrl(url);
}
return false;
}
});
}
private boolean canAsBgColor(int i) {
return Color.red(i) < 220 || Color.green(i) < 220 || Color.blue(i) < 220;
}
private void fetchColor() {
if (mWebView != null && mWebView.getVisibility() == View.VISIBLE && mWebView.getScrollX() < LuaUtil.dp2px(20)) {
mWebView.draw(canvas);
if (colorBitmap != null) {
int pixel = colorBitmap.getPixel(0, 0);
if (canAsBgColor(pixel)) {
layout_toolbar.setBackgroundColor(pixel);
if (pixel == Color.WHITE) {
setLightStatusBar();
} else {
setStatusBarColor(pixel);
}
}
}
}
}
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
return;
}
super.onBackPressed();
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
if (mWebView != null) {
if (mWebView.getParent() instanceof ViewGroup) {
((ViewGroup) mWebView.getParent()).removeAllViews();
}
mWebView.stopLoading();
mWebView.setWebChromeClient(null);
mWebView.setWebViewClient(null);
mWebView.removeAllViews();
mWebView.destroy();
mWebView = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
================================================
FILE: hydrogen-library/src/main/java/com/luajava/Console.java
================================================
package com.luajava;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Console {
public static void main(String[] args) {
try {
LuaState L = LuaStateFactory.newLuaState();
L.openLibs();
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
int res = L.LloadFile(args[i]);
if (res == 0) {
res = L.pcall(0, 0, 0);
}
if (res != 0) {
throw new LuaException("Error on file: " + args[i] + ". " + L.toString(-1));
}
}
return;
}
System.out.println("API Lua Java - console mode.");
BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
System.out.print("> ");
while (true) {
String line = inp.readLine();
if (line == null || line.equals("exit")) {
L.close();
} else {
int ret = L.LloadBuffer(line.getBytes(), "from console");
if (ret == 0) {
ret = L.pcall(0, 0, 0);
}
if (ret != 0) {
System.err.println("Error on line: " + line);
System.err.println(L.toString(-1));
}
System.out.print("> ");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
================================================
FILE: hydrogen-library/src/main/java/com/luajava/JavaFunction.java
================================================
package com.luajava;
public abstract class JavaFunction {
protected LuaState L;
public JavaFunction(LuaState L) {
this.L = L;
}
public abstract int execute() throws LuaException;
public LuaObject getParam(int idx) {
return this.L.getLuaObject(idx);
}
public void register(String name) throws LuaException {
synchronized (this.L) {
this.L.pushJavaFunction(this);
this.L.setGlobal(name);
}
}
}
================================================
FILE: hydrogen-library/src/main/java/com/luajava/LuaException.java
================================================
/*
* $Id: LuaException.java,v 1.6 2006/12/22 14:06:40 thiago Exp $
* Copyright (C) 2003-2007 Kepler Project.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.luajava;
/**
* LuaJava exception
*
* @author Thiago Ponte
*/
public class LuaException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public LuaException(String str) {
super(str);
}
/**
* Will work only on Java 1.4 or later.
* To work with Java 1.3, comment the first line and uncomment the second one.
*/
public LuaException(Exception e) {
super((e.getCause() != null) ? e.getCause() : e);
//super(e.getMessage());
}
}
================================================
FILE: hydrogen-library/src/main/java/com/luajava/LuaFunction.java
================================================
package com.luajava;
public class LuaFunction extends LuaObject implements LuaMetaTable {
protected LuaFunction(LuaState L, String globalName) {
super(L, globalName);
}
protected LuaFunction(LuaState L, int index) {
super(L, index);
}
@Override
public T __call(Object[] arg) throws LuaException {
// TODO: Implement this method
return (T) super.call(arg);
}
@Override
public Object __index(String key) {
// TODO: Implement this method
return null;
}
@Override
public void __newIndex(String key, Object value) {
// TODO: Implement this method
}
@Override
public T call(Object... args) throws LuaException {
// TODO: Implement this method
return (T) super.call(args);
}
}
================================================
FILE: hydrogen-library/src/main/java/com/luajava/LuaInvocationHandler.java
================================================
/*
* $Id: LuaInvocationHandler.java,v 1.4 2006/12/22 14:06:40 thiago Exp $
* Copyright (C) 2003-2007 Kepler Project.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.luajava;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* Class that implements the InvocationHandler interface.
* This class is used in the LuaJava's proxy system.
* When a proxy object is accessed, the method invoked is
* called from Lua
*
* @author Rizzato
* @author Thiago Ponte
*/
public class LuaInvocationHandler implements InvocationHandler {
private LuaObject obj;
private LuaState L;
private LuaObject print;
public LuaInvocationHandler(LuaObject obj) {
this.obj = obj;
L = obj.L;
print = L.getLuaObject("print");
}
/**
* Function called when a proxy object function is invoked.
*/
public Object invoke(Object proxy, Method method, Object[] args) throws LuaException {
synchronized (obj.L) {
String methodName = method.getName();
LuaObject func = obj.getField(methodName);
Class> retType = method.getReturnType();
if (func.isNil()) {
if (retType.equals(boolean.class) || retType.equals(Boolean.class))
return false;
else if (retType.isPrimitive() || Number.class.isAssignableFrom(retType))
return 0;
else
return null;
}
Object ret = null;
try {
// Checks if returned type is void. if it is returns null.
if (retType.equals(Void.class) || retType.equals(void.class)) {
func.call(args);
ret = null;
} else {
ret = func.call(args);
if (ret != null && ret instanceof Double) {
ret = LuaState.convertLuaNumber((Double) ret, retType);
}
}
} catch (LuaException e) {
print.call(methodName + " " + e.getMessage());
}
if (ret == null)
if (retType.equals(boolean.class) || retType.equals(Boolean.class))
return false;
else if (retType.isPrimitive() || Number.class.isAssignableFrom(retType))
return 0;
return ret;
}
}
}
================================================
FILE: hydrogen-library/src/main/java/com/luajava/LuaJavaAPI.java
================================================
/*
* $Id: LuaJavaAPI.java,v 1.4 2006/12/22 14:06:40 thiago Exp $
* Copyright (C) 2003-2007 Kepler Project.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Softwarea.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.luajava;
import android.util.Log;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Class that contains functions accessed by lua.
*
* @author Thiago Ponte
*/
public final class LuaJavaAPI {
public static HashMap methodsMap = new HashMap();
public static HashMap methodCache = new HashMap();
private static Class> LuaState_class = LuaState.class;
private static Class> String_class = String.class;
private static Class> List_class = List.class;
private static Class> ArrayList_class = ArrayList.class;
private static Class> HashMap_class = HashMap.class;
private static Class> Map_class = Map.class;
private static Class> LuaFunction_class = LuaFunction.class;
private static Class> LuaObject_class = LuaObject.class;
private static Class> LuaTable_class = LuaTable.class;
private static Class> Number_class = Number.class;
private static Class> Character_class = Character.class;
private LuaJavaAPI() {
}
/**
* Java implementation of the metamethod __index
*
* @param luaState int that indicates the state used
* @param obj Object to be indexed
* @param methodName the name of the method
* @return number of returned objects
*/
public static int objectIndex(long luaState, Object obj, String searchName, int type)
throws LuaException {
LuaState L = LuaStateFactory.getExistingState(luaState);
synchronized (L) {
int ret = 0;
if (type == 0)
if (checkMethod(L, obj, searchName) != 0)
return 2;
if (type == 0 || type == 1 || type == 5)
if ((ret = checkField(L, obj, searchName)) != 0)
return ret;
if (type == 0 || type == 4)
if (javaGetter(L, obj, searchName) != 0)
return 4;
if (type == 0 || type == 3)
if (checkClass(L, obj, searchName) != 0)
return 3;
if ((type == 0 || type == 6) && obj instanceof LuaMetaTable) {
Object res = ((LuaMetaTable) obj).__index(searchName);
L.pushObjectValue(res);
return 6;
}
return 0;
}
}
public static int callMethod(long luaState, Object obj, String cacheName)
throws LuaException {
LuaState L = LuaStateFactory.getExistingState(luaState);
synchronized (L) {
Method[] methods = methodCache.get(cacheName);
int top = L.getTop();
Object[] objs = new Object[top];
Method method = null;
// gets method and arguments
for (int i = 0; i < methods.length; i++) {
Class[] parameters = methods[i].getParameterTypes();
if (parameters.length != top)
continue;
boolean okMethod = true;
for (int j = 0; j < parameters.length; j++) {
try {
objs[j] = compareTypes(L, parameters[j], j + 1);
} catch (Exception e) {
okMethod = false;
break;
}
}
if (okMethod) {
method = methods[i];
break;
}
}
// If method is null means there isn't one receiving the given arguments
if (method == null) {
StringBuilder msgbuilder = new StringBuilder();
for (int i = 0; i < methods.length; i++) {
msgbuilder.append(methods[i].toString());
msgbuilder.append("\n");
}
throw new LuaException("Invalid method call. Invalid Parameters.\n" + msgbuilder.toString());
}
Object ret;
try {
if (!Modifier.isPublic(method.getModifiers()))
method.setAccessible(true);
ret = method.invoke(obj, objs);
} catch (Exception e) {
throw new LuaException(e);
}
// Void function returns null
if (ret == null && method.getReturnType().equals(Void.TYPE))
return 0;
// push result
L.pushObjectValue(ret);
return 1;
}
}
/**
* Java implementation of the metamethod __newindex
*
* @param luaState int that indicates the state used
* @param obj Object to be indexed
* @param searchName the name of the method
* @return number of returned objects
*/
public static int objectNewIndex(long luaState, Object obj, String searchName)
throws LuaException {
LuaState L = LuaStateFactory.getExistingState(luaState);
synchronized (L) {
int res;
res = setFieldValue(L, obj, searchName);
if (res != 0)
return 1;
res = javaSetter(L, obj, searchName);
if (res != 0)
return 1;
return 0;
}
}
public static int setFieldValue(LuaState L, Object obj, String fieldName) throws LuaException {
synchronized (L) {
Field field = null;
Class objClass;
boolean isClass = false;
if (obj == null)
return 0;
if (obj instanceof Class) {
objClass = (Class) obj;
isClass = true;
} else {
objClass = obj.getClass();
}
try {
field = objClass.getField(fieldName);
} catch (NoSuchFieldException e) {
/*try
{
field = objClass.getDeclaredField(fieldName);
}
catch (Exception e2)
*/
{
return 0;
}
}
if (field == null)
return 0;
if (isClass && !Modifier.isStatic(field.getModifiers()))
return 0;
Class type = field.getType();
try {
if (!Modifier.isPublic(field.getModifiers()))
field.setAccessible(true);
field.set(obj, compareTypes(L, type, 3));
} catch (LuaException e) {
argError(L, fieldName, 3, type);
} catch (Exception e) {
throw new LuaException(e);
}
return 1;
}
}
private static String argError(LuaState L, String name, int idx, Class type) throws LuaException {
throw new LuaException("bad argument to '" + name + "' (" + type.getName() + " expected, got " + typeName(L, 3) + " value)");
}
private static String typeName(LuaState L, int idx) throws LuaException {
if (L.isObject(idx)) {
return L.getObjectFromUserdata(idx).getClass().getName();
}
switch (L.type(idx)) {
case LuaState.LUA_TSTRING:
return "string";
case LuaState.LUA_TNUMBER:
return "number";
case LuaState.LUA_TBOOLEAN:
return "boolean";
case LuaState.LUA_TFUNCTION:
return "function";
case LuaState.LUA_TTABLE:
return "table";
case LuaState.LUA_TTHREAD:
return "thread";
case LuaState.LUA_TLIGHTUSERDATA:
case LuaState.LUA_TUSERDATA:
return "userdata";
}
return "unkown";
}
/**
* Java implementation of the metamethod __index
*
* @param luaState int that indicates the state used
* @param obj Object to be indexed
* @param methodName the name of the method
* @return number of returned objects
*/
public static int setArrayValue(long luaState, Object obj, int index) throws LuaException {
LuaState L = LuaStateFactory.getExistingState(luaState);
synchronized (L) {
if (obj.getClass().isArray()) {
Class> type = obj.getClass().getComponentType();
try {
Object value = compareTypes(L, type, 3);
Array.set(obj, index, value);
} catch (LuaException e) {
argError(L, obj.getClass().getName() + " [" + index + "]", 3, type);
}
} else if (obj instanceof List) {
((List