text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185 values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```java
package com.wooplr.spotlight.target;
import android.graphics.Point;
import android.graphics.Rect;
import android.view.View;
/**
* Created by jitender on 10/06/16.
*/
public class ViewTarget implements Target {
private View view;
public ViewTarget(View view) {
this.view = view;
}
@Override
public Point getPoint() {
int[] location = new int[2];
view.getLocationInWindow(location);
return new Point(location[0] + (view.getWidth() / 2), location[1] + (view.getHeight() / 2));
}
@Override
public Rect getRect() {
int[] location = new int[2];
view.getLocationInWindow(location);
return new Rect(
location[0],
location[1],
location[0] + view.getWidth(),
location[1] + view.getHeight()
);
}
@Override
public View getView() {
return view;
}
@Override
public int getViewLeft() {
return getRect().left;
}
@Override
public int getViewRight() {
return getRect().right;
}
@Override
public int getViewBottom() {
return getRect().bottom;
}
@Override
public int getViewTop() {
return getRect().top;
}
@Override
public int getViewWidth() {
return view.getWidth();
}
@Override
public int getViewHeight() {
return view.getHeight();
}
}
``` | /content/code_sandbox/Spotlight-library/src/main/java/com/wooplr/spotlight/target/ViewTarget.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 328 |
```java
package com.wooplr.spotlight.shape;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import com.wooplr.spotlight.target.Target;
/**
* Created by jitender on 10/06/16.
*/
public class Circle {
private Target target;
private int radius;
private Point circlePoint;
private int padding = 20;
public Circle(Target target, int padding) {
this.target = target;
this.padding = padding;
circlePoint = getFocusPoint();
calculateRadius(padding);
}
public void draw(Canvas canvas, Paint eraser, int padding) {
calculateRadius(padding);
circlePoint = getFocusPoint();
canvas.drawCircle(circlePoint.x, circlePoint.y, radius, eraser);
}
private Point getFocusPoint() {
return target.getPoint();
}
public void reCalculateAll() {
calculateRadius(padding);
circlePoint = getFocusPoint();
}
private void calculateRadius(int padding) {
int side;
int minSide = Math.min(target.getRect().width() / 2, target.getRect().height() / 2);
int maxSide = Math.max(target.getRect().width() / 2, target.getRect().height() / 2);
side = (minSide + maxSide) / 2;
radius = side + padding;
}
public int getRadius() {
return radius;
}
public Point getPoint() {
return circlePoint;
}
}
``` | /content/code_sandbox/Spotlight-library/src/main/java/com/wooplr/spotlight/shape/Circle.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 323 |
```java
package com.wooplr.spotlight.shape;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import com.wooplr.spotlight.target.AnimPoint;
import java.util.ArrayList;
import java.util.List;
/**
* Adapted from github.com/dupengtao/LineAnimation
*/
public class NormalLineAnimDrawable extends Drawable implements ValueAnimator.AnimatorUpdateListener {
private static final String FACTOR_X = "factorX";
private static final String FACTOR_Y = "factorY";
private final Path mPath2;
private final Paint mPaint2;
private float factorY, factorX;
private AnimPoint curAnimPoint = null;
private int moveTimes;
private List<AnimPoint> mAnimPoints = new ArrayList<AnimPoint>();
private ObjectAnimator mLineAnim;
private DisplayMode curDisplayMode = DisplayMode.Appear;
private long lineAnimDuration = 400;
private int lineColor = Color.parseColor("#eb273f");
private int lineStroke = 8;
private Animator.AnimatorListener mListner;
public NormalLineAnimDrawable() {
this(null);
}
public NormalLineAnimDrawable(Paint paint) {
mPath2 = new Path();
mPaint2 = paint == null ? getDefaultPaint() : paint;
}
private Paint getDefaultPaint() {
Paint p = new Paint();
p.setAntiAlias(true);
p.setDither(true);
p.setStyle(Paint.Style.STROKE);
p.setStrokeJoin(Paint.Join.ROUND);
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeWidth(lineStroke);
p.setColor(lineColor);
return p;
}
private ObjectAnimator getLineAnim() {
PropertyValuesHolder pvMoveY = PropertyValuesHolder.ofFloat(FACTOR_Y,
0f, 1f);
PropertyValuesHolder pvMoveX = PropertyValuesHolder.ofFloat(FACTOR_X,
0f, 1f);
ObjectAnimator lineAnim = ObjectAnimator.ofPropertyValuesHolder(
this, pvMoveY, pvMoveX).setDuration(lineAnimDuration);
lineAnim.setRepeatMode(ValueAnimator.RESTART);
lineAnim.setRepeatCount(mAnimPoints.size() - 1);
lineAnim.addUpdateListener(this);
if (android.os.Build.VERSION.SDK_INT > 17) {
lineAnim.setAutoCancel(true);
}
lineAnim.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
moveTimes = 0;
curAnimPoint = mAnimPoints.get(moveTimes);
if (mListner != null)
mListner.onAnimationStart(animation);
}
@Override
public void onAnimationEnd(Animator animation) {
if (mListner != null)
mListner.onAnimationEnd(animation);
}
@Override
public void onAnimationCancel(Animator animation) {
if (mListner != null)
mListner.onAnimationCancel(animation);
}
@Override
public void onAnimationRepeat(Animator animation) {
moveTimes++;
curAnimPoint = mAnimPoints.get(moveTimes);
if (mListner != null)
mListner.onAnimationRepeat(animation);
}
});
//lineAnim.addListener(mListner);
return lineAnim;
}
@NonNull
public void setmListner(Animator.AnimatorListener mListner) {
this.mListner = mListner;
}
public void playAnim(List<AnimPoint> animPoints) {
if (animPoints != null) {
mAnimPoints = animPoints;
}
if (mLineAnim == null) {
mLineAnim = getLineAnim();
}
if (mLineAnim.isRunning()) {
mLineAnim.cancel();
}
mLineAnim.start();
}
public void playAnim() {
playAnim(null);
}
public float getFactorY() {
return factorY;
}
public void setFactorY(float factorY) {
this.factorY = factorY;
}
public float getFactorX() {
return factorX;
}
public void setFactorX(float factorX) {
this.factorX = factorX;
}
@Override
public void onAnimationUpdate(ValueAnimator animation) {
invalidateSelf();
}
private void drawLine(List<AnimPoint> animPoints, int num) {
drawLine(animPoints, num, animPoints.size());
}
private void drawLine(List<AnimPoint> animPoints, int num, int size) {
for (int i = num, j = size; i < j; i++) {
AnimPoint p = animPoints.get(i);
mPath2.moveTo(p.getCurX(), p.getCurY());
mPath2.lineTo(p.getMoveX(), p.getMoveY());
}
}
public DisplayMode getCurDisplayMode() {
return curDisplayMode;
}
public void setCurDisplayMode(DisplayMode curDisplayMode) {
this.curDisplayMode = curDisplayMode;
}
@Override
public void draw(Canvas canvas) {
if (curAnimPoint != null) {
mPath2.rewind();
float curX = curAnimPoint.getCurX();
float curY = curAnimPoint.getCurY();
float moveX = curAnimPoint.getMoveX();
float moveY = curAnimPoint.getMoveY();
if (curDisplayMode == DisplayMode.Disappear) {
mPath2.moveTo(curX == moveX ? moveX : curX + ((moveX - curX) * factorX), curY == moveY ? moveY : curY + ((moveY - curY) * factorY));
mPath2.lineTo(moveX, moveY);
drawLine(mAnimPoints, moveTimes + 1);
} else if (curDisplayMode == DisplayMode.Appear) {
drawLine(mAnimPoints, 0, moveTimes);
mPath2.moveTo(curX, curY);
mPath2.lineTo(curX == moveX ? moveX : curX + ((moveX - curX) * factorX), curY == moveY ? moveY : curY + ((moveY - curY) * factorY));
}
canvas.drawPath(mPath2, mPaint2);
} else {
canvas.drawPath(mPath2, mPaint2);
}
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getOpacity() {
return 0;
}
public List<AnimPoint> getPoints() {
return mAnimPoints;
}
public void setPoints(List<AnimPoint> animPoints) {
mAnimPoints = animPoints;
}
public void setLineAnimDuration(long lineAnimDuration) {
this.lineAnimDuration = lineAnimDuration;
}
public void setLineColor(int lineColor) {
this.lineColor = lineColor;
}
public void setLineStroke(int lineStroke) {
this.lineStroke = lineStroke;
}
/**
* How to display the LineAnim
*/
public enum DisplayMode {
Disappear,
Appear,
}
}
``` | /content/code_sandbox/Spotlight-library/src/main/java/com/wooplr/spotlight/shape/NormalLineAnimDrawable.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 1,599 |
```java
package com.wooplr.spotlight.utils;
import android.content.res.Resources;
/**
* Created by jitender on 10/06/16.
*/
public class Utils {
public static int pxToDp(int px) {
return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}
public static int dpToPx(int dp) {
return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}
}
``` | /content/code_sandbox/Spotlight-library/src/main/java/com/wooplr/spotlight/utils/Utils.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 99 |
```java
package com.wooplr.spotlight.utils;
/**
* Created by Carlos Reyna on 30/07/16.
*/
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import com.wooplr.spotlight.SpotlightConfig;
import com.wooplr.spotlight.SpotlightView;
import com.wooplr.spotlight.prefs.PreferencesManager;
import java.util.LinkedList;
import java.util.Queue;
/**
* Class responsible for performing a sequence of
* spotlight animations one after the other.
*/
public class SpotlightSequence {
private Activity activity;
private SpotlightConfig config;
private Queue<SpotlightView.Builder> queue;
private static SpotlightSequence instance;
private final String TAG = "Tour Sequence";
/**
* Creates an instance of SpotlightSequence
* with an empty queue and a {@link SpotlightConfig} configuration
* @param activity where this sequence will be executed
* @param config {@link SpotlightConfig}
*/
private SpotlightSequence(Activity activity, SpotlightConfig config){
Log.d(TAG,"NEW TOUR_SEQUENCE INSTANCE");
this.activity = activity;
setConfig(config);
queue = new LinkedList<>();
}
/**
* Retriebes the current instance of SpotlightSequence
* @param activity where this sequence will be executed
* @param config {@link SpotlightConfig}
* @return If no instance was found. {@link SpotlightSequence()} will be called.
*/
public static SpotlightSequence getInstance(Activity activity, SpotlightConfig config){
if(instance == null){
instance = new SpotlightSequence(activity,config);
}
return instance;
}
/**
* Adds a new SpotlightView.Builder object to {@link this.queue}
* @param target View where the spotlight will focus
* @param title Spotlight title
* @param subtitle Spotlight subtitle
* * @param usageId id used to store the SpotlightView in {@link PreferencesManager}
* @return SpotlightSequence instance
*/
public SpotlightSequence addSpotlight(View target, String title, String subtitle, String usageId){
Log.d(TAG, "Adding " + usageId);
SpotlightView.Builder builder = new SpotlightView.Builder(activity)
.setConfiguration(config)
.headingTvText(title)
.usageId(usageId)
.subHeadingTvText(subtitle)
.target(target)
.setListener(new SpotlightListener() {
@Override
public void onUserClicked(String s) {
playNext();
}
})
.enableDismissAfterShown(true);
queue.add(builder);
return instance;
}
/**
* Adds a new SpotlightView.Builder object to {@link this.queue}
* @param target View where the spotlight will focus
* @param titleResId Spotlight title
* @param subTitleResId Spotlight subtitle
* @param usageId id used to store the SpotlightView in {@link PreferencesManager}
* @return SpotlightSequence instance
*/
public SpotlightSequence addSpotlight(@NonNull View target, int titleResId, int subTitleResId, String usageId){
String title = activity.getString(titleResId);
String subtitle = activity.getString(subTitleResId);
SpotlightView.Builder builder = new SpotlightView.Builder(activity)
.setConfiguration(config)
.headingTvText(title)
.usageId(usageId)
.subHeadingTvText(subtitle)
.target(target)
.setListener(new SpotlightListener() {
@Override
public void onUserClicked(String s) {
playNext();
}
})
.enableDismissAfterShown(true);
queue.add(builder);
return instance;
}
/**
* Starts the sequence.
*/
public void startSequence(){
if(queue.isEmpty()) {
Log.d(TAG, "EMPTY SEQUENCE");
}else{
queue.poll().show();
}
}
/**
* Free variables. Executed when the tour has finished
*/
private void resetTour() {
instance = null;
queue.clear();
this.activity = null;
config = null;
}
/**
* Executes the next Spotlight animation in the queue.
* If no more animations are found, resetTour()is called.
*/
private void playNext(){
SpotlightView.Builder next = queue.poll();
if(next != null){
// Log.d(TAG,"PLAYING NEXT SPOTLIGHT");
next.show().setReady(true);
}else {
Log.d(TAG, "END OF QUEUE");
resetTour();
}
}
/**
* Clear all Spotlights usageId from shared preferences.
* @param context
*/
public static void resetSpotlights(@NonNull Context context){
new PreferencesManager(context).resetAll();
}
/**
* Sets the specified {@link SpotlightConfig} configuration
* as the configuration to use.
* If no configuration is specified, the default configuration is used.
* @param config {@link SpotlightConfig}
*/
private void setConfig(@Nullable SpotlightConfig config) {
if(config == null){
config = new SpotlightConfig();
config.setLineAndArcColor(Color.parseColor("#eb273f"));
config.setDismissOnTouch(true);
config.setMaskColor(Color.argb(240,0,0,0));
config.setHeadingTvColor(Color.parseColor("#eb273f"));
config.setHeadingTvSize(32);
config.setSubHeadingTvSize(16);
config.setSubHeadingTvColor(Color.parseColor("#ffffff"));
config.setPerformClick(false);
config.setRevealAnimationEnabled(true);
config.setLineAnimationDuration(400);
}
this.config = config;
}
}
``` | /content/code_sandbox/Spotlight-library/src/main/java/com/wooplr/spotlight/utils/SpotlightSequence.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 1,215 |
```java
package com.wooplr.spotlight.utils;
/**
* Created by jitender on 10/06/16.
*/
public interface SpotlightListener {
void onUserClicked(String spotlightViewId);
}
``` | /content/code_sandbox/Spotlight-library/src/main/java/com/wooplr/spotlight/utils/SpotlightListener.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 43 |
```java
package com.wooplr.spotlight.prefs;
import android.content.Context;
import android.content.SharedPreferences;
public class PreferencesManager {
private static final String PREFERENCES_NAME = "spotlight_view_preferences";
private SharedPreferences sharedPreferences;
public PreferencesManager(Context context) {
sharedPreferences = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
}
public boolean isDisplayed(String id) {
return sharedPreferences.getBoolean(id, false);
}
public void setDisplayed(String id) {
sharedPreferences.edit().putBoolean(id, true).apply();
}
public void reset(String id) {
sharedPreferences.edit().remove(id).apply();
}
public void resetAll() {
sharedPreferences.edit().clear().apply();
}
}
``` | /content/code_sandbox/Spotlight-library/src/main/java/com/wooplr/spotlight/prefs/PreferencesManager.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 150 |
```java
package com.wooplr.spotlight;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="path_to_url">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
``` | /content/code_sandbox/Spotlight-library/src/test/java/com/wooplr/spotlight/ExampleUnitTest.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 90 |
```java
package com.wooplr.spotlight;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.MediumTest;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="path_to_url">Testing documentation</a>
*/
@MediumTest
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentationTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.wooplr.spotlight.test", appContext.getPackageName());
}
}
``` | /content/code_sandbox/Spotlight-library/src/androidTest/java/com/wooplr/spotlight/ExampleInstrumentationTest.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 164 |
```java
package com.example.spotlight;
import android.content.Context;
import android.graphics.Typeface;
import java.util.HashMap;
import java.util.Map;
/**
* Adapted from github.com/romannurik/muzei/
* <p/>
* Also see path_to_url
*/
public class FontUtil {
private FontUtil() {
}
private static final Map<String, Typeface> sTypefaceCache = new HashMap<String, Typeface>();
public static Typeface get(Context context, String font) {
synchronized (sTypefaceCache) {
if (!sTypefaceCache.containsKey(font)) {
Typeface tf = Typeface.createFromAsset(
context.getApplicationContext().getAssets(), font + ".ttf");
sTypefaceCache.put(font, tf);
}
return sTypefaceCache.get(font);
}
}
}
``` | /content/code_sandbox/app/src/main/java/com/example/spotlight/FontUtil.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 170 |
```java
package com.wooplr.spotlight;
import android.animation.Animator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PathEffect;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.PorterDuffXfermode;
import android.graphics.Typeface;
import android.graphics.drawable.AnimatedVectorDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.graphics.drawable.AnimatedVectorDrawableCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.wooplr.spotlight.prefs.PreferencesManager;
import com.wooplr.spotlight.shape.Circle;
import com.wooplr.spotlight.shape.NormalLineAnimDrawable;
import com.wooplr.spotlight.target.AnimPoint;
import com.wooplr.spotlight.target.Target;
import com.wooplr.spotlight.target.ViewTarget;
import com.wooplr.spotlight.utils.SpotlightListener;
import com.wooplr.spotlight.utils.Utils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jitender on 10/06/16.
*/
public class SpotlightView extends FrameLayout {
/**
* OverLay color
*/
private int maskColor = 0x70000000;
/**
* Intro Animation Duration
*/
private long introAnimationDuration = 400;
/**
* Toggel between reveal and fadein animation
*/
private boolean isRevealAnimationEnabled = true;
/**
* Final fadein text duration
*/
private long fadingTextDuration = 400;
/**
* Start intro once view is ready to show
*/
private boolean isReady;
/**
* Overlay circle above the view
*/
private Circle circleShape;
/**
* Target View
*/
private Target targetView;
/**
* Eraser to erase the circle area
*/
private Paint eraser;
/**
* Delay the intro view
*/
private Handler handler;
private Bitmap bitmap;
private Canvas canvas;
/**
* Padding for circle
*/
private int padding = 20;
/**
* View Width
*/
private int width;
/**
* View Height
*/
private int height;
/**
* Dismiss layout on touch
*/
private boolean dismissOnTouch;
private boolean dismissOnBackPress;
private boolean enableDismissAfterShown;
private PreferencesManager preferencesManager;
private String usageId;
/**
* Listener for spotLight when user clicks on the view
*/
private SpotlightListener listener;
/**
* Perform click when user clicks on the targetView
*/
private boolean isPerformClick;
/**
* Margin from left, right, top and bottom till the line will stop
*/
private int gutter = Utils.dpToPx(36);
/**
* Views Heading and sub-heading for spotlight
*/
private TextView subHeadingTv, headingTv;
/**
* Whether to show the arc at the end of the line that points to the target.
*/
private boolean showTargetArc = true;
/**
* Extra padding around the arc
*/
private int extraPaddingForArc = 24;
/**
* Defaults for heading TextView
*/
private int headingTvSize = 24;
private int headingTvSizeDimenUnit = -1;
private int headingTvColor = Color.parseColor("#eb273f");
private CharSequence headingTvText = "Hello";
/**
* Defaults for sub-heading TextView
*/
private int subHeadingTvSize = 24;
private int subHeadingTvSizeDimenUnit = -1;
private int subHeadingTvColor = Color.parseColor("#ffffff");
private CharSequence subHeadingTvText = "Hello";
/**
* Values for line animation
*/
private long lineAnimationDuration = 300;
private int lineStroke;
private PathEffect lineEffect;
private int lineAndArcColor = Color.parseColor("#eb273f");
private Typeface mTypeface = null;
private int softwareBtnHeight;
private boolean dismissCalled = false;
public SpotlightView(Context context) {
super(context);
init(context);
}
public SpotlightView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public SpotlightView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SpotlightView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
private void init(Context context) {
setWillNotDraw(false);
setVisibility(INVISIBLE);
lineStroke = Utils.dpToPx(4);
isReady = false;
isRevealAnimationEnabled = true;
dismissOnTouch = false;
isPerformClick = false;
enableDismissAfterShown = false;
dismissOnBackPress = false;
handler = new Handler();
preferencesManager = new PreferencesManager(context);
eraser = new Paint();
eraser.setColor(0xFFFFFFFF);
eraser.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
eraser.setFlags(Paint.ANTI_ALIAS_FLAG);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = getMeasuredWidth();
height = getMeasuredHeight();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
try{
if (!isReady) return;
if (bitmap == null || canvas == null) {
if (bitmap != null) bitmap.recycle();
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
this.canvas = new Canvas(bitmap);
}
this.canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
this.canvas.drawColor(maskColor);
circleShape.draw(this.canvas, eraser, padding);
canvas.drawBitmap(bitmap, 0, 0, null);
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float xT = event.getX();
float yT = event.getY();
int xV = circleShape.getPoint().x;
int yV = circleShape.getPoint().y;
int radius = circleShape.getRadius();
double dx = Math.pow(xT - xV, 2);
double dy = Math.pow(yT - yV, 2);
boolean isTouchOnFocus = (dx + dy) <= Math.pow(radius, 2);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (isTouchOnFocus && isPerformClick) {
targetView.getView().setPressed(true);
targetView.getView().invalidate();
}
return true;
case MotionEvent.ACTION_UP:
if (isTouchOnFocus || dismissOnTouch)
dismiss();
if (isTouchOnFocus && isPerformClick) {
targetView.getView().performClick();
targetView.getView().setPressed(true);
targetView.getView().invalidate();
targetView.getView().setPressed(false);
targetView.getView().invalidate();
}
return true;
default:
break;
}
return super.onTouchEvent(event);
}
/**
* Show the view based on the configuration
* Reveal is available only for Lollipop and above in other only fadein will work
* To support reveal in older versions use github.com/ozodrukh/CircularReveal
*
* @param activity
*/
private void show(final Activity activity) {
if (preferencesManager.isDisplayed(usageId))
return;
((ViewGroup) activity.getWindow().getDecorView()).addView(this);
setReady(true);
handler.postDelayed(new Runnable() {
@Override
public void run() {
try{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (isRevealAnimationEnabled)
startRevealAnimation(activity);
else {
startFadinAnimation(activity);
}
} else {
startFadinAnimation(activity);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
, 100);
}
/**
* Dissmiss view with reverse animation
*/
private void dismiss() {
if (dismissCalled) {
return;
}
dismissCalled = true;
preferencesManager.setDisplayed(usageId);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (isRevealAnimationEnabled)
exitRevealAnimation();
else
startFadeout();
} else {
startFadeout();
}
}
/**
* Revel animation from target center to screen width and height
*
* @param activity
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void startRevealAnimation(final Activity activity) {
float finalRadius = (float) Math.hypot(getViewWidth(), getHeight());
Animator anim = ViewAnimationUtils.createCircularReveal(this, targetView.getPoint().x, targetView.getPoint().y, 0, finalRadius);
anim.setInterpolator(AnimationUtils.loadInterpolator(activity,
android.R.interpolator.fast_out_linear_in));
anim.setDuration(introAnimationDuration);
anim.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
if (showTargetArc) {
addArcAnimation(activity);
} else {
addPathAnimation(activity);
}
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
setVisibility(View.VISIBLE);
if (dismissOnBackPress) {
requestFocus();
}
anim.start();
}
/**
* Reverse reveal animation
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void exitRevealAnimation() {
float finalRadius = (float) Math.hypot(getViewWidth(), getHeight());
Animator anim = ViewAnimationUtils.createCircularReveal(this, targetView.getPoint().x, targetView.getPoint().y, finalRadius, 0);
anim.setInterpolator(AnimationUtils.loadInterpolator(getContext(),
android.R.interpolator.accelerate_decelerate));
anim.setDuration(introAnimationDuration);
anim.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
setVisibility(GONE);
removeSpotlightView();
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
anim.start();
}
private void startFadinAnimation(final Activity activity) {
AlphaAnimation fadeIn = new AlphaAnimation(0.0f, 1.0f);
fadeIn.setDuration(introAnimationDuration);
fadeIn.setFillAfter(true);
fadeIn.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (showTargetArc) {
addArcAnimation(activity);
} else {
addPathAnimation(activity);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
setVisibility(VISIBLE);
if (dismissOnBackPress) {
requestFocus();
}
startAnimation(fadeIn);
}
private void startFadeout() {
AlphaAnimation fadeIn = new AlphaAnimation(1.0f, 0.0f);
fadeIn.setDuration(introAnimationDuration);
fadeIn.setFillAfter(true);
fadeIn.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
setVisibility(GONE);
removeSpotlightView();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
startAnimation(fadeIn);
}
/**
* Add arc above/below the circular target overlay.
*/
private void addArcAnimation(final Activity activity) {
AppCompatImageView mImageView = new AppCompatImageView(activity);
mImageView.setImageResource(R.drawable.ic_spotlight_arc);
LayoutParams params = new LayoutParams(2 * (circleShape.getRadius() + extraPaddingForArc),
2 * (circleShape.getRadius() + extraPaddingForArc));
if (targetView.getPoint().y > getHeight() / 2) {//bottom
if (targetView.getPoint().x > getWidth() / 2) {//Right
params.rightMargin = getWidth() - targetView.getPoint().x - circleShape.getRadius() - extraPaddingForArc;
params.bottomMargin = getHeight() - targetView.getPoint().y - circleShape.getRadius() - extraPaddingForArc;
params.gravity = Gravity.RIGHT | Gravity.BOTTOM;
} else {
params.leftMargin = targetView.getPoint().x - circleShape.getRadius() - extraPaddingForArc;
params.bottomMargin = getHeight() - targetView.getPoint().y - circleShape.getRadius() - extraPaddingForArc;
params.gravity = Gravity.LEFT | Gravity.BOTTOM;
}
} else {//up
mImageView.setRotation(180); //Reverse the view
if (targetView.getPoint().x > getWidth() / 2) {//Right
params.rightMargin = getWidth() - targetView.getPoint().x - circleShape.getRadius() - extraPaddingForArc;
params.bottomMargin = getHeight() - targetView.getPoint().y - circleShape.getRadius() - extraPaddingForArc;
params.gravity = Gravity.RIGHT | Gravity.BOTTOM;
} else {
params.leftMargin = targetView.getPoint().x - circleShape.getRadius() - extraPaddingForArc;
params.bottomMargin = getHeight() - targetView.getPoint().y - circleShape.getRadius() - extraPaddingForArc;
params.gravity = Gravity.LEFT | Gravity.BOTTOM;
}
}
mImageView.postInvalidate();
mImageView.setLayoutParams(params);
addView(mImageView);
PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(lineAndArcColor,
PorterDuff.Mode.SRC_ATOP);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AnimatedVectorDrawable avd = (AnimatedVectorDrawable)
ContextCompat.getDrawable(activity, R.drawable.avd_spotlight_arc);
avd.setColorFilter(porterDuffColorFilter);
mImageView.setImageDrawable(avd);
avd.start();
} else {
AnimatedVectorDrawableCompat avdc =
AnimatedVectorDrawableCompat.create(activity, R.drawable.avd_spotlight_arc);
avdc.setColorFilter(porterDuffColorFilter);
mImageView.setImageDrawable(avdc);
avdc.start();
}
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
addPathAnimation(activity);
}
}, 400);
}
private void addPathAnimation(Activity activity) {
View mView = new View(activity);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.width = getViewWidth();
params.height = getViewHeight();
// params.width = getMeasuredWidth();
// params.height = getMeasuredHeight();
addView(mView, params);
//Textviews
headingTv = new TextView(activity);
if (mTypeface != null)
headingTv.setTypeface(mTypeface);
if(headingTvSizeDimenUnit != -1)
headingTv.setTextSize(headingTvSizeDimenUnit,headingTvSize);
else
headingTv.setTextSize(headingTvSize);
headingTv.setVisibility(View.GONE);
headingTv.setTextColor(headingTvColor);
headingTv.setText(headingTvText);
subHeadingTv = new TextView(activity);
if (mTypeface != null)
subHeadingTv.setTypeface(mTypeface);
if(subHeadingTvSizeDimenUnit != -1)
subHeadingTv.setTextSize(subHeadingTvSizeDimenUnit,subHeadingTvSize);
else
subHeadingTv.setTextSize(subHeadingTvSize);
subHeadingTv.setTextColor(subHeadingTvColor);
subHeadingTv.setVisibility(View.GONE);
subHeadingTv.setText(subHeadingTvText);
//Line animation
Paint p = new Paint();
p.setAntiAlias(true);
p.setDither(true);
p.setStyle(Paint.Style.STROKE);
p.setStrokeJoin(Paint.Join.ROUND);
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeWidth(lineStroke);
p.setColor(lineAndArcColor);
p.setPathEffect(lineEffect);
NormalLineAnimDrawable animDrawable1 = new NormalLineAnimDrawable(p);
if (lineAnimationDuration > 0)
animDrawable1.setLineAnimDuration(lineAnimationDuration);
if (Build.VERSION.SDK_INT < 16) {
mView.setBackgroundDrawable(animDrawable1);
} else {
mView.setBackground(animDrawable1);
}
animDrawable1.setPoints(checkLinePoint());
animDrawable1.playAnim();
animDrawable1.setmListner(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
AlphaAnimation fadeIn = new AlphaAnimation(0.0f, 1.0f);
fadeIn.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if(enableDismissAfterShown)
dismissOnTouch = true;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
fadeIn.setDuration(fadingTextDuration);
fadeIn.setFillAfter(true);
headingTv.startAnimation(fadeIn);
subHeadingTv.startAnimation(fadeIn);
headingTv.setVisibility(View.VISIBLE);
subHeadingTv.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
}
private void enableDismissOnBackPress() {
setFocusableInTouchMode(true);
setFocusable(true);
requestFocus();
}
private List<AnimPoint> checkLinePoint() {
//Screen Height
int screenWidth = getWidth();
int screenHeight = getHeight();
List<AnimPoint> animPoints = new ArrayList<>();
//For TextViews
LayoutParams headingParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
LayoutParams subHeadingParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
//Spaces above and below the line
int spaceAboveLine = Utils.dpToPx(8);
int spaceBelowLine = Utils.dpToPx(12);
int extramargin = Utils.dpToPx(16);
//check up or down
if (targetView.getPoint().y > screenHeight / 2) {//Down TODO: add a logic for by 2
if (targetView.getPoint().x > screenWidth / 2) {//Right
animPoints.add(new AnimPoint((targetView.getViewRight() - targetView.getViewWidth() / 2),
targetView.getPoint().y - circleShape.getRadius() - extraPaddingForArc, (targetView.getViewRight() - targetView.getViewWidth() / 2),
targetView.getViewTop() / 2
));
animPoints.add(new AnimPoint((targetView.getViewRight() - targetView.getViewWidth() / 2),
targetView.getViewTop() / 2,
gutter,
targetView.getViewTop() / 2));
//TextViews
headingParams.leftMargin = gutter;
headingParams.rightMargin = screenWidth - (targetView.getViewRight() - targetView.getViewWidth() / 2) + extramargin;
headingParams.bottomMargin = screenHeight - targetView.getViewTop() / 2 + spaceAboveLine;
headingParams.topMargin = extramargin;
headingParams.gravity = Gravity.BOTTOM | Gravity.LEFT;
headingTv.setGravity(Gravity.LEFT);
subHeadingParams.rightMargin = screenWidth - (targetView.getViewRight() - targetView.getViewWidth() / 2) + extramargin;
subHeadingParams.leftMargin = gutter;
subHeadingParams.bottomMargin = extramargin;
subHeadingParams.topMargin = targetView.getViewTop() / 2 + spaceBelowLine;
subHeadingParams.gravity = Gravity.LEFT;
subHeadingTv.setGravity(Gravity.LEFT);
} else {//left
animPoints.add(new AnimPoint((targetView.getViewRight() - targetView.getViewWidth() / 2), targetView.getPoint().y - circleShape.getRadius() - extraPaddingForArc,
(targetView.getViewRight() - targetView.getViewWidth() / 2),
targetView.getViewTop() / 2
));
animPoints.add(new AnimPoint((targetView.getViewRight() - targetView.getViewWidth() / 2),
targetView.getViewTop() / 2,
screenWidth - ((screenHeight > screenWidth) ? gutter : (gutter + softwareBtnHeight)),
targetView.getViewTop() / 2));
//TextViews
if(screenHeight > screenWidth)
headingParams.rightMargin = gutter;//portrait
else
headingParams.rightMargin = gutter + softwareBtnHeight;//landscape
headingParams.leftMargin = (targetView.getViewRight() - targetView.getViewWidth() / 2) + extramargin;
headingParams.bottomMargin = screenHeight - targetView.getViewTop() / 2 + spaceAboveLine;
headingParams.topMargin = extramargin;
headingParams.gravity = Gravity.BOTTOM | Gravity.RIGHT;
headingTv.setGravity(Gravity.LEFT);
if(screenHeight > screenWidth)
subHeadingParams.rightMargin = gutter;//portrait
else
subHeadingParams.rightMargin = gutter + softwareBtnHeight;//landscape
subHeadingParams.leftMargin = (targetView.getViewRight() - targetView.getViewWidth() / 2) + extramargin;
subHeadingParams.topMargin = targetView.getViewTop() / 2 + spaceBelowLine;
subHeadingParams.bottomMargin = extramargin;
subHeadingParams.gravity = Gravity.RIGHT;
subHeadingTv.setGravity(Gravity.LEFT);
}
} else {//top
if (targetView.getPoint().x > screenWidth / 2) {//Right
animPoints.add(new AnimPoint(targetView.getViewRight() - targetView.getViewWidth() / 2,
targetView.getPoint().y + circleShape.getRadius() + extraPaddingForArc,
targetView.getViewRight() - targetView.getViewWidth() / 2,
(screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom()));
animPoints.add(new AnimPoint(targetView.getViewRight() - targetView.getViewWidth() / 2,
(screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom(),
gutter,
(screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom()));
// //TextViews
headingParams.leftMargin = gutter;
headingParams.rightMargin = screenWidth - (targetView.getViewRight() - targetView.getViewWidth() / 2) + extramargin;
headingParams.bottomMargin = screenHeight - ((screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom()) + spaceAboveLine;
headingParams.topMargin = extramargin;
headingParams.gravity = Gravity.BOTTOM | Gravity.LEFT;
headingTv.setGravity(Gravity.LEFT);
subHeadingParams.leftMargin = gutter;
subHeadingParams.rightMargin = screenWidth - targetView.getViewRight() + targetView.getViewWidth() / 2 + extramargin;
subHeadingParams.bottomMargin = extramargin;
subHeadingParams.topMargin = ((screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom()) + spaceBelowLine;
subHeadingParams.gravity = Gravity.LEFT;
subHeadingTv.setGravity(Gravity.LEFT);
} else {//left
animPoints.add(new AnimPoint(targetView.getViewRight() - targetView.getViewWidth() / 2,
targetView.getPoint().y + circleShape.getRadius() + extraPaddingForArc,
targetView.getViewRight() - targetView.getViewWidth() / 2,
(screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom()));
animPoints.add(new AnimPoint(targetView.getViewRight() - targetView.getViewWidth() / 2,
(screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom(),
screenWidth - ((screenHeight > screenWidth) ? gutter : (gutter + softwareBtnHeight)),
(screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom()));
// //TextViews
if(screenHeight > screenWidth)
headingParams.rightMargin = gutter;//portrait
else
headingParams.rightMargin = gutter + softwareBtnHeight;//landscape
headingParams.leftMargin = targetView.getViewRight() - targetView.getViewWidth() / 2 + extramargin;
headingParams.bottomMargin = screenHeight - ((screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom()) + spaceAboveLine;
headingParams.topMargin = extramargin;
headingParams.gravity = Gravity.BOTTOM | Gravity.RIGHT;
headingTv.setGravity(Gravity.LEFT);
if(screenHeight > screenWidth)
subHeadingParams.rightMargin = gutter;//portrait
else
subHeadingParams.rightMargin = gutter + softwareBtnHeight;//landscape
subHeadingParams.leftMargin = targetView.getViewRight() - targetView.getViewWidth() / 2 + extramargin;
subHeadingParams.bottomMargin = extramargin;
subHeadingParams.topMargin = ((screenHeight - targetView.getViewBottom()) / 2 + targetView.getViewBottom()) + spaceBelowLine;
subHeadingParams.gravity = Gravity.RIGHT;
subHeadingTv.setGravity(Gravity.LEFT);
}
}
addView(headingTv, headingParams);
addView(subHeadingTv, subHeadingParams);
return animPoints;
}
/**
* Remove the spotlight view
*/
private void removeSpotlightView() {
if (listener != null)
listener.onUserClicked(usageId);
if (getParent() != null)
((ViewGroup) getParent()).removeView(this);
}
/**
* Remove the spotlight view
* @param needOnUserClickedCallback true, if user wants a call back when this spotlight view is removed from parent.
*/
public void removeSpotlightView(boolean needOnUserClickedCallback) {
try{
if(needOnUserClickedCallback && listener != null)
listener.onUserClicked(usageId);
if (getParent() != null)
((ViewGroup) getParent()).removeView(this);
}catch(Exception e){
e.printStackTrace();
}
}
/**
* Setters
*/
public void setListener(SpotlightListener listener) {
this.listener = listener;
}
private void setMaskColor(int maskColor) {
this.maskColor = maskColor;
}
public void setReady(boolean ready) {
isReady = ready;
}
public void setPadding(int padding) {
this.padding = padding;
}
public void setDismissOnTouch(boolean dismissOnTouch) {
this.dismissOnTouch = dismissOnTouch;
}
public void setDismissOnBackPress(boolean dismissOnBackPress) {
this.dismissOnBackPress = dismissOnBackPress;
}
public boolean isEnableDismissAfterShown() {
return enableDismissAfterShown;
}
public void setEnableDismissAfterShown(boolean enableDismissAfterShown) {
this.enableDismissAfterShown = enableDismissAfterShown;
}
public void setPerformClick(boolean performClick) {
isPerformClick = performClick;
}
public void setExtraPaddingForArc(int extraPaddingForArc) {
this.extraPaddingForArc = extraPaddingForArc;
}
/**
* Whether to show the arc under/above the circular target overlay.
*
* @param show Set to true to show the arc line, false otherwise.
*/
public void setShowTargetArc(boolean show) {
this.showTargetArc = show;
}
public void setIntroAnimationDuration(long introAnimationDuration) {
this.introAnimationDuration = introAnimationDuration;
}
public void setRevealAnimationEnabled(boolean revealAnimationEnabled) {
isRevealAnimationEnabled = revealAnimationEnabled;
}
public void setFadingTextDuration(long fadingTextDuration) {
this.fadingTextDuration = fadingTextDuration;
}
public void setCircleShape(Circle circleShape) {
this.circleShape = circleShape;
}
public void setTargetView(Target targetView) {
this.targetView = targetView;
}
public void setUsageId(String usageId) {
this.usageId = usageId;
}
public void setHeadingTvSize(int headingTvSize) {
this.headingTvSize = headingTvSize;
}
public void setHeadingTvSize(int dimenUnit,int headingTvSize) {
this.headingTvSizeDimenUnit = dimenUnit;
this.headingTvSize = headingTvSize;
}
public void setHeadingTvColor(int headingTvColor) {
this.headingTvColor = headingTvColor;
}
public void setHeadingTvText(CharSequence headingTvText) {
this.headingTvText = headingTvText;
}
public void setSubHeadingTvSize(int subHeadingTvSize) {
this.subHeadingTvSize = subHeadingTvSize;
}
public void setSubHeadingTvSize(int dimenUnit, int subHeadingTvSize) {
this.subHeadingTvSizeDimenUnit = dimenUnit;
this.subHeadingTvSize = subHeadingTvSize;
}
public void setSubHeadingTvColor(int subHeadingTvColor) {
this.subHeadingTvColor = subHeadingTvColor;
}
public void setSubHeadingTvText(CharSequence subHeadingTvText) {
this.subHeadingTvText = subHeadingTvText;
}
public void setLineAnimationDuration(long lineAnimationDuration) {
this.lineAnimationDuration = lineAnimationDuration;
}
public void setLineAndArcColor(int lineAndArcColor) {
this.lineAndArcColor = lineAndArcColor;
}
public void setLineStroke(int lineStroke) {
this.lineStroke = lineStroke;
}
public void setLineEffect(PathEffect pathEffect) {
this.lineEffect = pathEffect;
}
private void setSoftwareBtnHeight(int px){
this.softwareBtnHeight = px;
}
public void setTypeface(Typeface typeface) {
this.mTypeface = typeface;
}
public void setConfiguration(SpotlightConfig configuration) {
if (configuration != null) {
this.maskColor = configuration.getMaskColor();
this.introAnimationDuration = configuration.getIntroAnimationDuration();
this.isRevealAnimationEnabled = configuration.isRevealAnimationEnabled();
this.fadingTextDuration = configuration.getFadingTextDuration();
this.padding = configuration.getPadding();
this.dismissOnTouch = configuration.isDismissOnTouch();
this.dismissOnBackPress = configuration.isDismissOnBackpress();
this.isPerformClick = configuration.isPerformClick();
this.headingTvSize = configuration.getHeadingTvSize();
this.headingTvSizeDimenUnit = configuration.getHeadingTvSizeDimenUnit();
this.headingTvColor = configuration.getHeadingTvColor();
this.headingTvText = configuration.getHeadingTvText();
this.subHeadingTvSize = configuration.getSubHeadingTvSize();
this.subHeadingTvSizeDimenUnit = configuration.getSubHeadingTvSizeDimenUnit();
this.subHeadingTvColor = configuration.getSubHeadingTvColor();
this.subHeadingTvText = configuration.getSubHeadingTvText();
this.lineAnimationDuration = configuration.getLineAnimationDuration();
this.lineStroke = configuration.getLineStroke();
this.lineAndArcColor = configuration.getLineAndArcColor();
}
}
/**
* Builder Class
*/
public static class Builder {
private SpotlightView spotlightView;
private Activity activity;
public Builder(Activity activity) {
this.activity = activity;
spotlightView = new SpotlightView(activity);
spotlightView.setSoftwareBtnHeight(getSoftButtonsBarHeight(activity));
}
public Builder maskColor(int maskColor) {
spotlightView.setMaskColor(maskColor);
return this;
}
public Builder introAnimationDuration(long delayMillis) {
spotlightView.setIntroAnimationDuration(delayMillis);
return this;
}
public Builder enableRevealAnimation(boolean isFadeAnimationEnabled) {
spotlightView.setRevealAnimationEnabled(isFadeAnimationEnabled);
return this;
}
public Builder target(View view) {
spotlightView.setTargetView(new ViewTarget(view));
return this;
}
public Builder targetPadding(int padding) {
spotlightView.setPadding(padding);
return this;
}
public Builder dismissOnTouch(boolean dismissOnTouch) {
spotlightView.setDismissOnTouch(dismissOnTouch);
return this;
}
public Builder dismissOnBackPress(boolean dismissOnBackPress) {
spotlightView.setDismissOnBackPress(dismissOnBackPress);
return this;
}
public Builder usageId(String usageId) {
spotlightView.setUsageId(usageId);
return this;
}
public Builder setTypeface(Typeface typeface) {
spotlightView.setTypeface(typeface);
return this;
}
public Builder setListener(SpotlightListener spotlightListener) {
spotlightView.setListener(spotlightListener);
return this;
}
public Builder performClick(boolean isPerformClick) {
spotlightView.setPerformClick(isPerformClick);
return this;
}
public Builder fadeinTextDuration(long fadinTextDuration) {
spotlightView.setFadingTextDuration(fadinTextDuration);
return this;
}
public Builder headingTvSize(int headingTvSize) {
spotlightView.setHeadingTvSize(headingTvSize);
return this;
}
public Builder headingTvSize(int dimenUnit, int headingTvSize) {
spotlightView.setHeadingTvSize(dimenUnit,headingTvSize);
return this;
}
public Builder headingTvColor(int color) {
spotlightView.setHeadingTvColor(color);
return this;
}
public Builder headingTvText(CharSequence text) {
spotlightView.setHeadingTvText(text);
return this;
}
public Builder subHeadingTvSize(int headingTvSize) {
spotlightView.setSubHeadingTvSize(headingTvSize);
return this;
}
public Builder subHeadingTvSize(int dimenUnit, int headingTvSize) {
spotlightView.setSubHeadingTvSize(dimenUnit,headingTvSize);
return this;
}
public Builder subHeadingTvColor(int color) {
spotlightView.setSubHeadingTvColor(color);
return this;
}
public Builder subHeadingTvText(CharSequence text) {
spotlightView.setSubHeadingTvText(text);
return this;
}
public Builder lineAndArcColor(int color) {
spotlightView.setLineAndArcColor(color);
return this;
}
public Builder lineAnimDuration(long duration) {
spotlightView.setLineAnimationDuration(duration);
return this;
}
public Builder showTargetArc(boolean show) {
spotlightView.setShowTargetArc(show);
return this;
}
public Builder enableDismissAfterShown(boolean enable) {
if (enable) {
spotlightView.setEnableDismissAfterShown(enable);
spotlightView.setDismissOnTouch(false);
}
return this;
}
public Builder lineStroke(int stroke) {
spotlightView.setLineStroke(Utils.dpToPx(stroke));
return this;
}
public Builder lineEffect(@Nullable PathEffect pathEffect) {
spotlightView.setLineEffect(pathEffect);
return this;
}
public Builder setConfiguration(SpotlightConfig configuration) {
spotlightView.setConfiguration(configuration);
return this;
}
public SpotlightView build() {
Circle circle = new Circle(
spotlightView.targetView,
spotlightView.padding);
spotlightView.setCircleShape(circle);
if (spotlightView.dismissOnBackPress) {
spotlightView.enableDismissOnBackPress();
}
return spotlightView;
}
public SpotlightView show() {
build().show(activity);
return spotlightView;
}
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (dismissOnBackPress && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (event.getAction() == KeyEvent.ACTION_UP) {
dismiss();
}
return true;
}
return super.dispatchKeyEvent(event);
}
public void logger(String s) {
Log.d("Spotlight", s);
}
private int getViewHeight(){
if(getWidth() > getHeight()){
//Landscape
return getHeight();
}else{
//Portrait
return (getHeight() - softwareBtnHeight);
}
}
private int getViewWidth(){
if(getWidth() > getHeight()){
//Landscape
return (getWidth() - softwareBtnHeight);
}else{
//Portrait
return getWidth();
}
}
private static int getSoftButtonsBarHeight(Activity activity) {
try{
// getRealMetrics is only available with API 17 and +
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
if(metrics.heightPixels > metrics.widthPixels)
{
//Portrait
int usableHeight = metrics.heightPixels;
activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
int realHeight = metrics.heightPixels;
if (realHeight > usableHeight)
return realHeight - usableHeight;
else
return 0;
}else{
//Landscape
int usableHeight = metrics.widthPixels;
activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
int realHeight = metrics.widthPixels;
if (realHeight > usableHeight)
return realHeight - usableHeight;
else
return 0;
}
}
}catch(Exception e){
e.printStackTrace();
}
return 0;
}
/**
* This will remove all usage ids from preferences.
*/
public void resetAllUsageIds(){
try{
preferencesManager.resetAll();
}catch(Exception e){
e.printStackTrace();
}
}
/**
* This will remove given usage id from preferences.
* @param id Spotlight usage id to be removed
*/
public void resetUsageId(String id){
try{
preferencesManager.reset(id);
}catch(Exception e){
e.printStackTrace();
}
}
}
``` | /content/code_sandbox/Spotlight-library/src/main/java/com/wooplr/spotlight/SpotlightView.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 8,475 |
```java
package com.example.spotlight;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.wooplr.spotlight.SpotlightView;
import com.wooplr.spotlight.prefs.PreferencesManager;
import com.wooplr.spotlight.utils.SpotlightSequence;
import com.wooplr.spotlight.utils.Utils;
import java.util.Random;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// static {
// AppCompatDelegate.setCompatVectorFromSourcesEnabled(true);
// }
private FloatingActionButton fab;
private static final String INTRO_CARD = "fab_intro";
private static final String INTRO_SWITCH = "switch_intro";
private static final String INTRO_RESET = "reset_intro";
private static final String INTRO_REPEAT = "repeat_intro";
private static final String INTRO_CHANGE_POSITION = "change_position_intro";
private static final String INTRO_SEQUENCE = "sequence_intro";
private boolean isRevealEnabled = true;
private SpotlightView spotLight;
@BindView(R.id.switchAnimation)
TextView switchAnimation;
@BindView(R.id.reset)
TextView reset;
@BindView(R.id.resetAndPlay)
TextView resetAndPlay;
@BindView(R.id.changePosAndPlay)
TextView changePosAndPlay;
@BindView(R.id.startSequence)
TextView startSequence;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Fab Clicked!", Toast.LENGTH_LONG).show();
}
});
switchAnimation.setOnClickListener(this);
reset.setOnClickListener(this);
resetAndPlay.setOnClickListener(this);
changePosAndPlay.setOnClickListener(this);
startSequence.setOnClickListener(this);
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
showIntro(fab, INTRO_CARD);
}
}, 2400);
}
@Override
public void onClick(View view) {
PreferencesManager mPreferencesManager = new PreferencesManager(MainActivity.this);
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int screenWidth = displaymetrics.widthPixels;
int screenHeight = displaymetrics.heightPixels;
switch (view.getId()) {
case R.id.switchAnimation:
if (isRevealEnabled) {
switchAnimation.setText("Switch to Reveal");
isRevealEnabled = false;
} else {
switchAnimation.setText("Switch to Fadein");
isRevealEnabled = true;
}
mPreferencesManager.resetAll();
break;
case R.id.reset:
mPreferencesManager.resetAll();
break;
case R.id.resetAndPlay:
mPreferencesManager.resetAll();
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
showIntro(fab, INTRO_CARD);
}
}, 400);
break;
case R.id.changePosAndPlay:
mPreferencesManager.resetAll();
Random r = new Random();
int right = r.nextInt((screenWidth - Utils.dpToPx(16)) - 16) + 16;
int bottom = r.nextInt((screenHeight - Utils.dpToPx(16)) - 16) + 16;
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
params.setMargins(Utils.dpToPx(16), Utils.dpToPx(16), right, bottom);
fab.setLayoutParams(params);
break;
case R.id.startSequence:
mPreferencesManager.resetAll();
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
SpotlightSequence.getInstance(MainActivity.this,null)
.addSpotlight(switchAnimation, "Switch Animation", "Click to swtich the animation", INTRO_SWITCH)
.addSpotlight(reset, "Reset ", "Click here to reset preferences", INTRO_RESET)
.addSpotlight(resetAndPlay, "Play Again", "Click here to play again", INTRO_REPEAT)
.addSpotlight(changePosAndPlay, "Change Position", "Click here to change position and replay", INTRO_CHANGE_POSITION)
.addSpotlight(startSequence, "Start sequence", "Well.. you just clicked here", INTRO_SEQUENCE)
.addSpotlight(fab,"Love", "Like the picture?\n" + "Let others know.", INTRO_CARD)
.startSequence();
}
},400);
break;
}
}
private void showIntro(View view, String usageId) {
spotLight = new SpotlightView.Builder(this)
.introAnimationDuration(400)
.enableRevealAnimation(isRevealEnabled)
.performClick(true)
.fadeinTextDuration(400)
//.setTypeface(FontUtil.get(this, "RemachineScript_Personal_Use"))
.headingTvColor(Color.parseColor("#eb273f"))
.headingTvSize(32)
.headingTvText("Love")
.subHeadingTvColor(Color.parseColor("#ffffff"))
.subHeadingTvSize(16)
.subHeadingTvText("Like the picture?\nLet others know.")
.maskColor(Color.parseColor("#dc000000"))
.target(view)
.lineAnimDuration(400)
.lineAndArcColor(Color.parseColor("#eb273f"))
.dismissOnTouch(true)
.dismissOnBackPress(true)
.enableDismissAfterShown(true)
.usageId(usageId) //UNIQUE ID
.show();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(spotLight.isShown()){
spotLight.removeSpotlightView(false);//Remove current spotlight view from parent
resetAndPlay.performClick();//Show it again in new orientation if required.
}
}
}
``` | /content/code_sandbox/app/src/main/java/com/example/spotlight/MainActivity.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 1,356 |
```java
package com.example.spotlight;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="path_to_url">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
``` | /content/code_sandbox/app/src/test/java/com/example/spotlight/ExampleUnitTest.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 87 |
```java
package com.example.spotlight;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.MediumTest;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="path_to_url">Testing documentation</a>
*/
@MediumTest
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentationTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.spotlight", appContext.getPackageName());
}
}
``` | /content/code_sandbox/app/src/androidTest/java/com/example/spotlight/ExampleInstrumentationTest.java | java | 2016-06-14T11:34:35 | 2024-08-14T04:14:09 | Spotlight | 29jitender/Spotlight | 1,272 | 157 |
```qmake
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/JVillella/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# path_to_url
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
``` | /content/code_sandbox/greedo-layout/proguard-rules.pro | qmake | 2016-02-05T20:57:07 | 2024-06-26T02:59:30 | greedo-layout-for-android | 500px/greedo-layout-for-android | 1,638 | 142 |
```java
package com.fivehundredpx.greedolayout;
/**
* Created by Julian Villella on 16-02-23.
*/
public class Size {
int mWidth;
int mHeight;
public Size(int width, int height) {
mWidth = width;
mHeight = height;
}
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
}
``` | /content/code_sandbox/greedo-layout/src/main/java/com/fivehundredpx/greedolayout/Size.java | java | 2016-02-05T20:57:07 | 2024-06-26T02:59:30 | greedo-layout-for-android | 500px/greedo-layout-for-android | 1,638 | 94 |
```java
package com.fivehundredpx.greedolayout;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Julian Villella on 15-08-24.
*/
public class GreedoLayoutSizeCalculator {
public interface SizeCalculatorDelegate {
double aspectRatioForIndex(int index);
}
private static final int DEFAULT_MAX_ROW_HEIGHT = 600;
private int mMaxRowHeight = DEFAULT_MAX_ROW_HEIGHT;
private static final int INVALID_CONTENT_WIDTH = -1;
private int mContentWidth = INVALID_CONTENT_WIDTH;
// When in fixed height mode and the item's width is less than this percentage, don't try to
// fit the item, overflow it to the next row and grow the existing items.
private static final double VALID_ITEM_SLACK_THRESHOLD = 2.0 / 3.0;
private boolean mIsFixedHeight = false;
private SizeCalculatorDelegate mSizeCalculatorDelegate;
private List<Size> mSizeForChildAtPosition;
private List<Integer> mFirstChildPositionForRow;
private List<Integer> mRowForChildPosition;
public GreedoLayoutSizeCalculator(SizeCalculatorDelegate sizeCalculatorDelegate) {
mSizeCalculatorDelegate = sizeCalculatorDelegate;
mSizeForChildAtPosition = new ArrayList<>();
mFirstChildPositionForRow = new ArrayList<>();
mRowForChildPosition = new ArrayList<>();
}
public void setContentWidth(int contentWidth) {
if (mContentWidth != contentWidth) {
mContentWidth = contentWidth;
reset();
}
}
public int getContentWidth() {
return mContentWidth;
}
public void setMaxRowHeight(int maxRowHeight) {
if (mMaxRowHeight != maxRowHeight) {
mMaxRowHeight = maxRowHeight;
reset();
}
}
public void setFixedHeight(boolean fixedHeight) {
if (mIsFixedHeight != fixedHeight) {
mIsFixedHeight = fixedHeight;
reset();
}
}
public Size sizeForChildAtPosition(int position) {
if (position >= mSizeForChildAtPosition.size()) {
computeChildSizesUpToPosition(position);
}
return mSizeForChildAtPosition.get(position);
}
public int getFirstChildPositionForRow(int row) {
if (row >= mFirstChildPositionForRow.size()) {
computeFirstChildPositionsUpToRow(row);
}
return mFirstChildPositionForRow.get(row);
}
public int getRowForChildPosition(int position) {
if (position >= mRowForChildPosition.size()) {
computeChildSizesUpToPosition(position);
}
return mRowForChildPosition.get(position);
}
public void reset() {
mSizeForChildAtPosition.clear();
mFirstChildPositionForRow.clear();
mRowForChildPosition.clear();
}
private void computeFirstChildPositionsUpToRow(int row) {
// TODO: Rewrite this? Looks dangerous but in reality should be fine. I'd like something
// less alarming though.
while (row >= mFirstChildPositionForRow.size()) {
computeChildSizesUpToPosition(mSizeForChildAtPosition.size() + 1);
}
}
private void computeChildSizesUpToPosition(int lastPosition) {
if (mContentWidth == INVALID_CONTENT_WIDTH) {
throw new RuntimeException("Invalid content width. Did you forget to set it?");
}
if (mSizeCalculatorDelegate == null) {
throw new RuntimeException("Size calculator delegate is missing. Did you forget to set it?");
}
int firstUncomputedChildPosition = mSizeForChildAtPosition.size();
int row = mRowForChildPosition.size() > 0
? mRowForChildPosition.get(mRowForChildPosition.size() - 1) + 1 : 0;
double currentRowAspectRatio = 0.0;
List<Double> itemAspectRatios = new ArrayList<>();
int currentRowHeight = mIsFixedHeight ? mMaxRowHeight : Integer.MAX_VALUE;
int currentRowWidth = 0;
int pos = firstUncomputedChildPosition;
while (pos <= lastPosition || (mIsFixedHeight ? currentRowWidth <= mContentWidth : currentRowHeight > mMaxRowHeight)) {
double posAspectRatio = mSizeCalculatorDelegate.aspectRatioForIndex(pos);
// If the size calculator delegate supplies negative aspect ratio,
// consider it as "span the entire row" view. It will force a line break
// and add the view to its own line
boolean isFullRowView = false;
if (posAspectRatio < 0) {
isFullRowView = true;
} else{
currentRowAspectRatio += posAspectRatio;
itemAspectRatios.add(posAspectRatio);
}
currentRowWidth = calculateWidth(currentRowHeight, currentRowAspectRatio);
if (!mIsFixedHeight) {
currentRowHeight = calculateHeight(mContentWidth, currentRowAspectRatio);
}
boolean isRowFull = mIsFixedHeight ? currentRowWidth > mContentWidth : currentRowHeight <= mMaxRowHeight;
if (isRowFull || isFullRowView) {
int rowChildCount = itemAspectRatios.size();
// If the current view is the full row view, the current row is forced to wrap so that
// the full row view can take the entire row for itself, however the first
// children on that row needs to be added to mFirstChildPositionForRow as well, otherwise
// the item decoration will not work
if (isFullRowView) {
mFirstChildPositionForRow.add(pos - rowChildCount);
}
mFirstChildPositionForRow.add(pos - rowChildCount + 1);
int[] itemSlacks = new int[rowChildCount];
if (mIsFixedHeight) {
itemSlacks = distributeRowSlack(currentRowWidth, rowChildCount, itemAspectRatios);
if (rowChildCount > 1 && !hasValidItemSlacks(itemSlacks, itemAspectRatios)) {
int lastItemWidth = calculateWidth(currentRowHeight,
itemAspectRatios.get(itemAspectRatios.size() - 1));
currentRowWidth -= lastItemWidth;
rowChildCount -= 1;
--pos;
itemAspectRatios.remove(itemAspectRatios.size() - 1);
itemSlacks = distributeRowSlack(currentRowWidth, rowChildCount, itemAspectRatios);
}
}
int availableSpace = mContentWidth;
for (int i = 0; i < rowChildCount; i++) {
// If the previous row was force-wrapped and there was a single photo, the row
// size would be computed from that single photo - this could make the row huge
// because the aspect ratio of that single photo would be used. So this limits
// it to something reasonable
if (isFullRowView && !isRowFull) {
currentRowHeight = (int) Math.ceil(mMaxRowHeight * 0.75);
}
int itemWidth = calculateWidth(currentRowHeight, itemAspectRatios.get(i)) - itemSlacks[i];
itemWidth = Math.min(availableSpace, itemWidth);
mSizeForChildAtPosition.add(new Size(itemWidth, currentRowHeight));
mRowForChildPosition.add(row);
availableSpace -= itemWidth;
}
// Now add a size for the full row view
if (isFullRowView) {
mSizeForChildAtPosition.add(new Size(mContentWidth, calculateHeight(mContentWidth, Math.abs(posAspectRatio))));
mRowForChildPosition.add(row++);
}
itemAspectRatios.clear();
currentRowAspectRatio = 0.0;
row++;
}
pos++;
}
}
private int[] distributeRowSlack(int rowWidth, int rowChildCount, List<Double> itemAspectRatios) {
return distributeRowSlack(rowWidth - mContentWidth, rowWidth, rowChildCount, itemAspectRatios);
}
private int[] distributeRowSlack(int rowSlack, int rowWidth, int rowChildCount, List<Double> itemAspectRatios) {
int itemSlacks[] = new int[rowChildCount];
for (int i = 0; i < rowChildCount; i++) {
double itemWidth = mMaxRowHeight * itemAspectRatios.get(i);
itemSlacks[i] = (int) (rowSlack * (itemWidth / rowWidth));
}
return itemSlacks;
}
private boolean hasValidItemSlacks(int[] itemSlacks, List<Double> itemAspectRatios) {
for (int i = 0; i < itemSlacks.length; i++) {
int itemWidth = (int) (itemAspectRatios.get(i) * mMaxRowHeight);
if (!isValidItemSlack(itemSlacks[i], itemWidth)) {
return false;
}
}
return true;
}
private boolean isValidItemSlack(int itemSlack, int itemWidth) {
return (itemWidth - itemSlack) / (double) itemWidth > VALID_ITEM_SLACK_THRESHOLD;
}
private int calculateWidth(int itemHeight, double aspectRatio) {
return (int) Math.ceil(itemHeight * aspectRatio);
}
private int calculateHeight(int itemWidth, double aspectRatio) {
return (int) Math.ceil(itemWidth / aspectRatio);
}
}
``` | /content/code_sandbox/greedo-layout/src/main/java/com/fivehundredpx/greedolayout/GreedoLayoutSizeCalculator.java | java | 2016-02-05T20:57:07 | 2024-06-26T02:59:30 | greedo-layout-for-android | 500px/greedo-layout-for-android | 1,638 | 2,028 |
```java
package com.fivehundredpx.greedolayout;
import android.graphics.Rect;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
/**
* Created by Julian Villella on 15-07-30.
*/
public class GreedoSpacingItemDecoration extends RecyclerView.ItemDecoration {
private static final String TAG = GreedoSpacingItemDecoration.class.getName();
public static int DEFAULT_SPACING = 64;
private int mSpacing;
public GreedoSpacingItemDecoration() {
this(DEFAULT_SPACING);
}
public GreedoSpacingItemDecoration(int spacing) {
mSpacing = spacing;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (!(parent.getLayoutManager() instanceof GreedoLayoutManager)) {
throw new IllegalArgumentException(String.format("The %s must be used with a %s",
GreedoSpacingItemDecoration.class.getSimpleName(),
GreedoLayoutManager.class.getSimpleName()));
}
final GreedoLayoutManager layoutManager = (GreedoLayoutManager) parent.getLayoutManager();
int childIndex = parent.getChildAdapterPosition(view);
if (childIndex == RecyclerView.NO_POSITION) return;
outRect.top = 0;
outRect.bottom = mSpacing;
outRect.left = 0;
outRect.right = mSpacing;
// Add inter-item spacings
if (isTopChild(childIndex, layoutManager)) {
outRect.top = mSpacing;
}
if (isLeftChild(childIndex, layoutManager)) {
outRect.left = mSpacing;
}
}
protected static boolean isTopChild(int position, GreedoLayoutManager layoutManager) {
boolean isFirstViewHeader = layoutManager.isFirstViewHeader();
if (isFirstViewHeader && position == GreedoLayoutManager.HEADER_POSITION) {
return true;
} else if (isFirstViewHeader && position > GreedoLayoutManager.HEADER_POSITION) {
// Decrement position to factor in existence of header
position -= 1;
}
final GreedoLayoutSizeCalculator sizeCalculator = layoutManager.getSizeCalculator();
return sizeCalculator.getRowForChildPosition(position) == 0;
}
protected static boolean isLeftChild(int position, GreedoLayoutManager layoutManager) {
boolean isFirstViewHeader = layoutManager.isFirstViewHeader();
if (isFirstViewHeader && position == GreedoLayoutManager.HEADER_POSITION) {
return true;
} else if (isFirstViewHeader && position > GreedoLayoutManager.HEADER_POSITION) {
// Decrement position to factor in existence of header
position -= 1;
}
final GreedoLayoutSizeCalculator sizeCalculator = layoutManager.getSizeCalculator();
int rowForPosition = sizeCalculator.getRowForChildPosition(position);
return sizeCalculator.getFirstChildPositionForRow(rowForPosition) == position;
}
}
``` | /content/code_sandbox/greedo-layout/src/main/java/com/fivehundredpx/greedolayout/GreedoSpacingItemDecoration.java | java | 2016-02-05T20:57:07 | 2024-06-26T02:59:30 | greedo-layout-for-android | 500px/greedo-layout-for-android | 1,638 | 583 |
```java
package com.fivehundredpx.greedolayout;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.fivehundredpx.greedolayout.GreedoLayoutSizeCalculator.SizeCalculatorDelegate;
/**
* Created by Julian Villella on 15-08-24.
*/
// TODO: When measuring children we can likely pass getContentWidth() as their widthUsed
public class GreedoLayoutManager extends RecyclerView.LayoutManager {
private static final String TAG = GreedoLayoutManager.class.getSimpleName();
// Position of the header, which is the same value as its row. They can be used interchangeably
static final int HEADER_POSITION = 0;
// An invalid scroll position value
static final int INVALID_SCROLL_POSITION = -1;
// TODO: Can we do away with this?
private enum Direction { NONE, UP, DOWN }
// First (top-left) position visible at any point
private int mFirstVisiblePosition;
// First (top) row position at any given point
private int mFirstVisibleRow;
// Flag to force current scroll offsets to be ignored on re-layout
private boolean mForceClearOffsets;
// Scroll position offset that will be applied on the next layout pass
private int mPendingScrollPositionOffset = 0;
// Flag to indicate that the first item should be treated as a header. Note: The size calculator
// doesn't factor in the existence of a header. That is left to the layout manager. This also
// means, that the positions used to query the size calculator should be offset by -1 if we are
// using a header.
private boolean mIsFirstViewHeader;
// The size of the header view. This is calculated in {@code preFillGrid}.
private Size mHeaderViewSize;
// Adapter position that the view will be scrolled to after layout passes
private int mPendingScrollPosition = INVALID_SCROLL_POSITION;
// This allows Greedo to layout only a fixed number of rows, any views from further rows
// will remain detached and therefore hidden
private int mRowsLimit = -1;
private GreedoLayoutSizeCalculator mSizeCalculator;
public GreedoLayoutManager(SizeCalculatorDelegate sizeCalculatorDelegate) {
mSizeCalculator = new GreedoLayoutSizeCalculator(sizeCalculatorDelegate);
}
/**
* Set to true if you want all rows to be of the same height. The height will be equal to the
* value passed to {@code setMaxRowHeight(int)}.
*
* @param fixedHeight true to ensure all rows will have the same height.
*/
public void setFixedHeight(boolean fixedHeight) {
mSizeCalculator.setFixedHeight(fixedHeight);
}
/**
* The max height a row could be. If fixed height is enabled via {@code setFixedHeight(boolean)}
* the given max row height value will be used as the fixed row height.
*
* @param maxRowHeight Max height a row can grow to.
*/
public void setMaxRowHeight(int maxRowHeight) {
mSizeCalculator.setMaxRowHeight(maxRowHeight);
}
/**
* Set to true if you want the first view to act as a header. It's height will be obtained from
* the view itself, and the width will be equal to the content width.
*
* @param isFirstViewHeader true to have the first view act as a header.
*/
public void setFirstViewAsHeader(boolean isFirstViewHeader) {
mIsFirstViewHeader = isFirstViewHeader;
}
public boolean isFirstViewHeader() {
return mIsFirstViewHeader;
}
/**
* Set this if you want a fixed amount of rows to be laid out. If the adapter has
* more items than fits these rows, they will remain hidden. Set to -1 to disable.
*
* @param rows the amount of rows to layout
*/
public void setFixedNumberOfRows(int rows) {
mRowsLimit = rows;
}
// The initial call from the framework, received when we need to start laying out the initial
// set of views, or when the user changes the data set
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
// We have nothing to show for an empty data set but clear any existing views
if (getItemCount() == 0) {
detachAndScrapAttachedViews(recycler);
return;
}
mSizeCalculator.setContentWidth(getContentWidth());
mSizeCalculator.reset();
int initialTopOffset = 0;
if (getChildCount() == 0) { // First or empty layout
mFirstVisiblePosition = 0;
mFirstVisibleRow = 0;
} else { // Adapter data set changes
// Keep the existing initial position, and save off the current scrolled offset.
final View topChild = getChildAt(0);
if (mForceClearOffsets) {
initialTopOffset = 0;
mForceClearOffsets = false;
} else {
initialTopOffset = getDecoratedTop(topChild);
}
}
detachAndScrapAttachedViews(recycler);
preFillGrid(Direction.NONE, 0, initialTopOffset, recycler, state);
mPendingScrollPositionOffset = 0;
}
@Override
public void onAdapterChanged(RecyclerView.Adapter oldAdapter, RecyclerView.Adapter newAdapter) {
removeAllViews();
mSizeCalculator.reset();
}
/**
* Find first visible position, scrap all children, and then layout all visible views returning
* the number of pixels laid out, which could be greater than the entire view (useful for scroll
* functions).
* @param direction The direction we are filling the grid in
* @param dy Vertical offset, creating a gap that we need to fill
* @param emptyTop Offset we begin filling at
* @return Number of vertical pixels laid out
*/
private int preFillGrid(Direction direction, int dy, int emptyTop,
RecyclerView.Recycler recycler, RecyclerView.State state) {
int newFirstVisiblePosition = firstChildPositionForRow(mFirstVisibleRow);
// First, detach all existing views from the layout. detachView() is a lightweight operation
// that we can use to quickly reorder views without a full add/remove.
SparseArray<View> viewCache = new SparseArray<>(getChildCount());
int startLeftOffset = getPaddingLeft();
int startTopOffset = getPaddingTop() + emptyTop;
if (getChildCount() != 0) {
startTopOffset = getDecoratedTop(getChildAt(0));
if (mFirstVisiblePosition != newFirstVisiblePosition) {
switch (direction) {
case UP: // new row above may be shown
double previousTopRowHeight = sizeForChildAtPosition(
mFirstVisiblePosition - 1).getHeight();
startTopOffset -= previousTopRowHeight;
break;
case DOWN: // row may have gone off screen
double topRowHeight = sizeForChildAtPosition(
mFirstVisiblePosition).getHeight();
startTopOffset += topRowHeight;
break;
}
}
// Cache all views by their existing position, before updating counts
for (int i = 0; i < getChildCount(); i++) {
int position = mFirstVisiblePosition + i;
final View child = getChildAt(i);
viewCache.put(position, child);
}
// Temporarily detach all cached views. Views we still need will be added back at the proper index
for (int i = 0; i < viewCache.size(); i++) {
final View cachedView = viewCache.valueAt(i);
detachView(cachedView);
}
}
mFirstVisiblePosition = newFirstVisiblePosition;
// Next, supply the grid of items that are deemed visible. If they were previously there,
// they will simply be re-attached. New views that must be created are obtained from
// the Recycler and added.
int leftOffset = startLeftOffset;
int topOffset = startTopOffset + mPendingScrollPositionOffset;
int nextPosition = mFirstVisiblePosition;
int currentRow = 0;
while (nextPosition >= 0 && nextPosition < state.getItemCount()) {
boolean isViewCached = true;
View view = viewCache.get(nextPosition);
if (view == null) {
view = recycler.getViewForPosition(nextPosition);
isViewCached = false;
}
if (mIsFirstViewHeader && nextPosition == HEADER_POSITION) {
measureChildWithMargins(view, 0, 0);
mHeaderViewSize = new Size(view.getMeasuredWidth(), view.getMeasuredHeight());
}
// Overflow to next row if we don't fit
Size viewSize = sizeForChildAtPosition(nextPosition);
if ((leftOffset + viewSize.getWidth()) > getContentWidth()) {
// Break if the rows limit has been hit
if (currentRow + 1 == mRowsLimit) break;
currentRow++;
leftOffset = startLeftOffset;
Size previousViewSize = sizeForChildAtPosition(nextPosition - 1);
topOffset += previousViewSize.getHeight();
}
// These next children would no longer be visible, stop here
boolean isAtEndOfContent;
switch (direction) {
case DOWN: isAtEndOfContent = topOffset >= getContentHeight() + dy; break;
default: isAtEndOfContent = topOffset >= getContentHeight(); break;
}
if (isAtEndOfContent) break;
if (isViewCached) {
// Re-attach the cached view at its new index
attachView(view);
viewCache.remove(nextPosition);
} else {
addView(view);
measureChildWithMargins(view, 0, 0);
int right = leftOffset + viewSize.getWidth();
int bottom = topOffset + viewSize.getHeight();
layoutDecorated(view, leftOffset, topOffset, right, bottom);
}
leftOffset += viewSize.getWidth();
nextPosition++;
}
// Scrap and store views that were not re-attached (no longer visible).
for (int i = 0; i < viewCache.size(); i++) {
final View removingView = viewCache.valueAt(i);
recycler.recycleView(removingView);
}
// Calculate pixels laid out during fill
int pixelsFilled = 0;
if (getChildCount() > 0) {
pixelsFilled = getChildAt(getChildCount() - 1).getBottom();
}
return pixelsFilled;
}
@Override
public void onLayoutCompleted(RecyclerView.State state) {
super.onLayoutCompleted(state);
// Run pending scroll if there's any
if (mPendingScrollPosition != INVALID_SCROLL_POSITION) {
scrollToPosition(mPendingScrollPosition);
mPendingScrollPosition = INVALID_SCROLL_POSITION;
}
}
private int getContentWidth() {
return getWidth() - getPaddingLeft() - getPaddingRight();
}
private int getContentHeight() {
return getHeight() - getPaddingTop() - getPaddingBottom();
}
//region SizeCalculator proxy methods
private Size sizeForChildAtPosition(int position) {
if (mIsFirstViewHeader && position == HEADER_POSITION) {
return mHeaderViewSize;
} else if (mIsFirstViewHeader && position > HEADER_POSITION) {
// Decrement position to factor in existence of header
position -= 1;
}
return mSizeCalculator.sizeForChildAtPosition(position);
}
private int rowForChildPosition(int position) {
int offset = 0;
if (mIsFirstViewHeader && position == HEADER_POSITION) {
return HEADER_POSITION;
} else if (mIsFirstViewHeader && position > HEADER_POSITION) {
// Decrement position to factor in existence of header
position -= 1;
offset = 1;
}
return mSizeCalculator.getRowForChildPosition(position) + offset;
}
private int firstChildPositionForRow(int row) {
int offset = 0;
if (mIsFirstViewHeader && row == HEADER_POSITION) {
return HEADER_POSITION;
} else if (mIsFirstViewHeader && row > HEADER_POSITION) {
// Decrement row to factor in existence of header
row -= 1;
offset = 1;
}
return mSizeCalculator.getFirstChildPositionForRow(row) + offset;
}
//endregion
/**
* {@inheritDoc}
*/
@Override
public void scrollToPosition(int position) {
if (position >= getItemCount()) {
Log.w(TAG, String.format("Cannot scroll to %d, item count is %d", position, getItemCount()));
return;
}
// Scrolling can only be performed once the layout knows its own sizing
// so defer the scrolling request after the postLayout pass
if (mSizeCalculator.getContentWidth() <= 0) {
mPendingScrollPosition = position;
return;
}
mForceClearOffsets = true; // Ignore current scroll offset
mFirstVisibleRow = rowForChildPosition(position);
mFirstVisiblePosition = firstChildPositionForRow(mFirstVisibleRow);
requestLayout();
}
/**
* Scroll to the specified adapter position with the given offset. Note that the scroll position
* change will not be reflected until the next layout call. If you are just trying to make a
* position visible, use {@link #scrollToPosition(int)}.
*
* @param position Index (starting at 0) of the reference item.
* @param offset The distance (in pixels) between the start edge of the item view and
* start edge of the RecyclerView.
* @see #scrollToPosition(int)
*/
public void scrollToPositionWithOffset(int position, int offset) {
mPendingScrollPositionOffset = offset;
scrollToPosition(position);
}
@Override
public boolean canScrollVertically() {
return true;
}
@Override
public int computeVerticalScrollOffset(RecyclerView.State state) {
View topLeftView = getChildAt(0);
return topLeftView == null ? 0 : Math.abs(getDecoratedTop(topLeftView));
}
@Override
public int computeVerticalScrollRange(@NonNull RecyclerView.State state) {
View bottomRightView = getChildAt(getChildCount() - 1);
return bottomRightView == null ? 0 : getDecoratedBottom(bottomRightView);
}
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
if (getChildCount() == 0 || dy == 0) {
return 0;
}
final View topLeftView = getChildAt(0);
final View bottomRightView = getChildAt(getChildCount() - 1);
int pixelsFilled = getContentHeight();
// TODO: Split into methods, or a switch case?
if (dy > 0) {
boolean isLastChildVisible = (mFirstVisiblePosition + getChildCount()) >= getItemCount();
if (isLastChildVisible) {
// Is at end of content
pixelsFilled = Math.max(getDecoratedBottom(bottomRightView) - getContentHeight(), 0);
} else if (getDecoratedBottom(topLeftView) - dy <= 0) {
// Top row went offscreen
mFirstVisibleRow++;
pixelsFilled = preFillGrid(Direction.DOWN, Math.abs(dy), 0, recycler, state);
} else if (getDecoratedBottom(bottomRightView) - dy < getContentHeight()) {
// New bottom row came on screen
pixelsFilled = preFillGrid(Direction.DOWN, Math.abs(dy), 0, recycler, state);
}
} else {
if (mFirstVisibleRow == 0 && getDecoratedTop(topLeftView) - dy >= 0) {
// Is scrolled to top
pixelsFilled = -getDecoratedTop(topLeftView);
} else if (getDecoratedTop(topLeftView) - dy >= 0) {
// New top row came on screen
mFirstVisibleRow--;
pixelsFilled = preFillGrid(Direction.UP, Math.abs(dy), 0, recycler, state);
} else if (getDecoratedTop(bottomRightView) - dy > getContentHeight()) {
// Bottom row went offscreen
pixelsFilled = preFillGrid(Direction.UP, Math.abs(dy), 0, recycler, state);
}
}
final int scrolled = Math.abs(dy) > pixelsFilled ? (int) Math.signum(dy) * pixelsFilled : dy;
offsetChildrenVertical(-scrolled);
// Return value determines if a boundary has been reached (for edge effects and flings). If
// returned value does not match original delta (passed in), RecyclerView will draw an
// edge effect.
return scrolled;
}
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new RecyclerView.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
}
/**
* Returns the adapter position of the first visible view.
*
* @return The adapter position of the first visible view or {@link RecyclerView#NO_POSITION} if
* there aren't any visible items.
*/
public int findFirstVisibleItemPosition() {
if (getItemCount() == 0) {
return RecyclerView.NO_POSITION;
} else {
return mFirstVisiblePosition;
}
}
/**
* Returns the adapter position of the last visible view.
*
* @return The adapter position of the last visible view or {@link RecyclerView#NO_POSITION} if
* there aren't any visible items.
*/
public int findLastVisibleItemPosition() {
if (getItemCount() == 0) {
return RecyclerView.NO_POSITION;
} else {
return mFirstVisiblePosition + getChildCount();
}
}
public GreedoLayoutSizeCalculator getSizeCalculator() {
return mSizeCalculator;
}
}
``` | /content/code_sandbox/greedo-layout/src/main/java/com/fivehundredpx/greedolayout/GreedoLayoutManager.java | java | 2016-02-05T20:57:07 | 2024-06-26T02:59:30 | greedo-layout-for-android | 500px/greedo-layout-for-android | 1,638 | 3,907 |
```java
package com.fivehundredpx.greedo_layout_sample;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.fivehundredpx.greedolayout.GreedoLayoutManager;
import com.fivehundredpx.greedolayout.GreedoSpacingItemDecoration;
/**
* Created by Julian Villella on 16-02-24.
*/
public class SampleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
PhotosAdapter photosAdapter = new PhotosAdapter(this);
final GreedoLayoutManager layoutManager = new GreedoLayoutManager(photosAdapter);
layoutManager.setMaxRowHeight(MeasUtils.dpToPx(150, this));
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(photosAdapter);
int spacing = MeasUtils.dpToPx(4, this);
recyclerView.addItemDecoration(new GreedoSpacingItemDecoration(spacing));
findViewById(R.id.toggle_fixed_height).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
layoutManager.setFixedHeight(((ToggleButton) view).isChecked());
layoutManager.requestLayout();
}
});
}
}
``` | /content/code_sandbox/greedo-layout-sample/src/main/java/com/fivehundredpx/greedo_layout_sample/SampleActivity.java | java | 2016-02-05T20:57:07 | 2024-06-26T02:59:30 | greedo-layout-for-android | 500px/greedo-layout-for-android | 1,638 | 321 |
```java
package com.fivehundredpx.greedo_layout_sample;
import android.app.ActivityManager;
import android.app.Application;
import com.squareup.picasso.LruCache;
import com.squareup.picasso.Picasso;
import static android.content.pm.ApplicationInfo.FLAG_LARGE_HEAP;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.HONEYCOMB;
/**
* Created by Julian Villella on 16-02-24.
*/
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
Picasso picasso = new Picasso.Builder(this)
.memoryCache(new LruCache(calculateMemoryCacheSize()))
.build();
Picasso.setSingletonInstance(picasso);
}
private int calculateMemoryCacheSize() {
ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
boolean largeHeap = (getApplicationInfo().flags & FLAG_LARGE_HEAP) != 0;
int memoryClass = am.getMemoryClass();
if (largeHeap && SDK_INT >= HONEYCOMB) {
memoryClass = am.getLargeMemoryClass();
}
// Target ~50% of the available heap.
return 1024 * 1024 * memoryClass / 2;
}
}
``` | /content/code_sandbox/greedo-layout-sample/src/main/java/com/fivehundredpx/greedo_layout_sample/App.java | java | 2016-02-05T20:57:07 | 2024-06-26T02:59:30 | greedo-layout-for-android | 500px/greedo-layout-for-android | 1,638 | 259 |
```java
package com.fivehundredpx.greedo_layout_sample;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.recyclerview.widget.RecyclerView;
import com.fivehundredpx.greedolayout.GreedoLayoutSizeCalculator.SizeCalculatorDelegate;
import com.squareup.picasso.Picasso;
/**
* Created by Julian Villella on 16-02-24.
*/
public class PhotosAdapter extends RecyclerView.Adapter<PhotosAdapter.PhotoViewHolder> implements SizeCalculatorDelegate {
private static final int IMAGE_COUNT = 500; // number of images adapter will show
private final int[] mImageResIds = Constants.IMAGES;
private final double[] mImageAspectRatios = new double[Constants.IMAGES.length];
private Context mContext;
@Override
public double aspectRatioForIndex(int index) {
// Precaution, have better handling for this in greedo-layout
if (index >= getItemCount()) return 1.0;
return mImageAspectRatios[getLoopedIndex(index)];
}
public class PhotoViewHolder extends RecyclerView.ViewHolder {
private ImageView mImageView;
public PhotoViewHolder(ImageView imageView) {
super(imageView);
mImageView = imageView;
}
}
public PhotosAdapter(Context context) {
mContext = context;
calculateImageAspectRatios();
}
@Override
public PhotoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ImageView imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
));
return new PhotoViewHolder(imageView);
}
@Override
public void onBindViewHolder(PhotoViewHolder holder, int position) {
Picasso.with(mContext)
.load(mImageResIds[getLoopedIndex(position)])
.into(holder.mImageView);
}
@Override
public int getItemCount() {
return IMAGE_COUNT;
}
private void calculateImageAspectRatios() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
for (int i = 0; i < mImageResIds.length; i++) {
BitmapFactory.decodeResource(mContext.getResources(), mImageResIds[i], options);
mImageAspectRatios[i] = options.outWidth / (double) options.outHeight;
}
}
// Index gets wrapped around <code>Constants.IMAGES.length</code> so we can loop content.
private int getLoopedIndex(int index) {
return index % Constants.IMAGES.length; // wrap around
}
}
``` | /content/code_sandbox/greedo-layout-sample/src/main/java/com/fivehundredpx/greedo_layout_sample/PhotosAdapter.java | java | 2016-02-05T20:57:07 | 2024-06-26T02:59:30 | greedo-layout-for-android | 500px/greedo-layout-for-android | 1,638 | 552 |
```java
package com.fivehundredpx.greedo_layout_sample;
import android.content.Context;
import android.util.TypedValue;
/**
* Created by Julian Villella on 15-08-05.
*/
public class MeasUtils {
public static int pxToDp(int px, Context context) {
return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, px,
context.getResources().getDisplayMetrics());
}
public static int dpToPx(float dp, Context context) {
return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
context.getResources().getDisplayMetrics());
}
}
``` | /content/code_sandbox/greedo-layout-sample/src/main/java/com/fivehundredpx/greedo_layout_sample/MeasUtils.java | java | 2016-02-05T20:57:07 | 2024-06-26T02:59:30 | greedo-layout-for-android | 500px/greedo-layout-for-android | 1,638 | 134 |
```java
package com.fivehundredpx.greedo_layout_sample;
import androidx.annotation.DrawableRes;
/**
* Created by Julian Villella on 16-02-24.
*/
public class Constants {
public static final @DrawableRes int[] IMAGES = new int[] {
R.drawable.photo_1,
R.drawable.photo_2,
R.drawable.photo_3,
R.drawable.photo_4,
R.drawable.photo_5,
R.drawable.photo_6,
R.drawable.photo_7,
R.drawable.photo_8,
R.drawable.photo_9,
R.drawable.photo_10,
R.drawable.photo_11,
R.drawable.photo_12,
R.drawable.photo_13,
R.drawable.photo_14,
R.drawable.photo_15,
R.drawable.photo_16,
R.drawable.photo_17
};
}
``` | /content/code_sandbox/greedo-layout-sample/src/main/java/com/fivehundredpx/greedo_layout_sample/Constants.java | java | 2016-02-05T20:57:07 | 2024-06-26T02:59:30 | greedo-layout-for-android | 500px/greedo-layout-for-android | 1,638 | 177 |
```python
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Author : XueWeiHan
# E-mail : 595666367@qq.com
# Date : 16/10/21 1:41
# Desc : HelloGitHub
"""
HelloGitHub
"""
from __future__ import print_function
import sys
import os
CONTENT_FLAG = '{{ hello_github_content }}'
NUM_FLAG = '{{ hello_github_num }}'
class InputError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
def check_path(path):
"""
"""
if not os.path.exists(path):
print('not exist: {path}'.format(path=path))
return False
else:
return True
def read_file(input_path):
with open(input_path, 'r') as fb:
return fb.read()
def write_file(output_path, output_data):
with open(output_path, 'w') as fb:
fb.write(output_data)
def make_content(num):
template_path = os.path.join(os.path.abspath(os.curdir), 'template.md')
output_path = os.path.join(os.path.abspath(os.curdir), num)
content_path = os.path.join(output_path, 'content'+num+'.md')
if not (check_path(content_path) and check_path(template_path)):
# content template
return None
temple_data = read_file(template_path).replace(NUM_FLAG, num)
content_data = read_file(content_path)
output_data = temple_data.replace(CONTENT_FLAG, content_data)
write_file(os.path.join(output_path, 'HelloGitHub{num}.md'.format(num=num)), output_data)
print('Make GitHub{num} successful'.format(num=num))
def make_all_content():
dir_list = os.listdir(os.path.abspath(os.curdir))
for fi_dir in dir_list:
# script
if os.path.isdir(fi_dir) and 'script' not in fi_dir:
make_content(fi_dir)
def main():
"""
"""
input_list = sys.argv #
if len(input_list) != 2:
raise InputError('Input error: Need a param')
else:
try:
input_arg = input_list[1]
except Exception:
raise InputError('Input error: Must be number')
if len(input_arg) == 1:
make_content('0' + input_arg)
elif input_arg == 'all':
make_all_content()
else:
make_content(input_arg)
if __name__ == '__main__':
main()
``` | /content/code_sandbox/script/make_content/make_content.py | python | 2016-05-04T06:24:11 | 2024-08-16T19:26:01 | HelloGitHub | 521xueweihan/HelloGitHub | 89,301 | 564 |
```python
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Author : XueWeiHan
# E-mail : 595666367@qq.com
# Date : 16/8/30 10:43
# Desc : Github Bot
import os
import logging
import smtplib
import datetime
from operator import itemgetter
from email.mime.text import MIMEText
from email.header import Header
import requests
logging.basicConfig(
level=logging.WARNING,
filename=os.path.join(os.path.dirname(__file__), 'bot_log.txt'),
filemode='a',
format='%(name)s %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'
)
logger = logging.getLogger('Bot') # log
# github
ACCOUNT = {
'username': '',
'password': ''
}
API = {
'events': 'path_to_url{username}/received_events'.format(username=ACCOUNT['username'])
}
#
MAIL = {
'mail': '', #
'username': '',
'password': '',
'host': 'smtp.qq.com',
'port': 465
}
#
RECEIVERS = []
#
DAY = 1
# stars
STARS = 100
# qqpath_to_url
CONTENT_FORMAT = """
<table border="2" align="center">
<tr>
<th></th>
<th></th>
<th></th>
<th>starred </th>
<th> star </th>
</tr>
{project_info_string}
</table>
"""
def get_data(page=1):
"""
path_to_url
GitHub 30 300
"""
args = '?page={page}'.format(page=page)
response = requests.get(API['events']+args,
auth=(ACCOUNT['username'], ACCOUNT['password']))
status_code = response.status_code
if status_code == 200:
resp_json = response.json()
return resp_json
else:
logging.error(' event api ', status_code)
return []
def get_all_data():
"""
300
path_to_url
GitHub 30 300
"""
all_data_list = []
for i in range(10):
response_json = get_data(i+1)
if response_json:
all_data_list.extend(response_json)
return all_data_list
def check_condition(data):
"""
"""
create_time = datetime.datetime.strptime(
data['created_at'], "%Y-%m-%dT%H:%M:%SZ") + datetime.timedelta(hours=8)
date_condition = create_time >= (datetime.datetime.now()
- datetime.timedelta(days=DAY))
if (data['type'] == 'WatchEvent') and date_condition:
# star
if data['payload']['action'] == 'started' and \
ACCOUNT['username'] not in data['repo']['name']:
data['date_time'] = create_time.strftime("%Y-%m-%d %H:%M:%S")
return True
else:
return False
def analyze(json_data):
"""
:return
"""
result_data = []
for fi_data in json_data:
if check_condition(fi_data):
result_data.append(fi_data)
return result_data
def get_stars(data):
"""
starsstars
"""
project_info_list = []
for fi_data in data:
project_info = dict()
project_info['user'] = fi_data['actor']['login']
project_info['user_url'] = 'path_to_url + project_info['user']
project_info['avatar_url'] = fi_data['actor']['avatar_url']
project_info['repo_name'] = fi_data['repo']['name']
project_info['repo_url'] = 'path_to_url + project_info['repo_name']
project_info['date_time'] = fi_data['date_time']
try:
repo_stars = requests.get(fi_data['repo']['url'], timeout=2).json()
if repo_stars:
project_info['repo_stars'] = int(repo_stars['stargazers_count'])
else:
project_info['repo_stars'] = -1
except Exception as e:
project_info['repo_stars'] = -1
logger.warning(u'{} {}'.format(
project_info['repo_name'], e))
finally:
if project_info['repo_stars'] >= STARS or project_info['repo_stars'] == -1:
# star
project_info_list.append(project_info)
project_info_list = sorted(project_info_list, key=itemgetter('repo_stars'), reverse=True)
return project_info_list
def make_content():
"""
"""
json_data = get_all_data()
data = analyze(json_data)
content = []
project_info_list = get_stars(data)
for project_info in project_info_list:
project_info_string = """<tr>
<td><img src={avatar_url} width=32px></img></td>
<td><a href={user_url}>{user}</a></td>
<td><a href={repo_url}>{repo_name}</a></td>
<td>{date_time}</td>
<td>{repo_stars}</td>
</tr>
""".format(**project_info)
content.append(project_info_string)
return content
def send_email(receivers, email_content):
"""
"""
sender = MAIL['mail'] #
receivers = receivers #
# html utf-8
message = MIMEText(
CONTENT_FORMAT.format(project_info_string=''.join(email_content)),
'html', 'utf-8'
)
message['From'] = Header(u'GitHub ', 'utf-8')
message['To'] = Header(u'', 'utf-8')
subject = u' GitHub ' #
message['Subject'] = Header(subject, 'utf-8')
try:
smtp_obj = smtplib.SMTP_SSL() # qqhttpsSMTP_SSL
smtp_obj.connect(MAIL['host'], MAIL['port']) # SMTP
smtp_obj.login(MAIL['username'], MAIL['password'])
smtp_obj.sendmail(sender, receivers, message.as_string())
except smtplib.SMTPException as e:
logger.error(u": {}".format(e))
if __name__ == '__main__':
content = make_content()
send_email(RECEIVERS, content)
``` | /content/code_sandbox/script/github_bot/github_bot.py | python | 2016-05-04T06:24:11 | 2024-08-16T19:26:01 | HelloGitHub | 521xueweihan/HelloGitHub | 89,301 | 1,387 |
```javascript
// ==UserScript==
// @name GitHub
// @description GitHub
// @copyright 2016, (path_to_url
// @icon path_to_url
// @version 1.6.4
// @author
// @license MIT
// @homepageURL path_to_url
// @match path_to_url
// @match path_to_url
// @require path_to_url
// @run-at document-end
// @grant none
// ==/UserScript==
(function (window, document, undefined) {
'use strict';
var lang = 'zh'; //
// 2016-04-18 github jquery amd
// var $ = require('github/jquery')['default'];
//
var page = getPage();
transTitle(); //
timeElement(); //
// setTimeout(contributions, 100); // (ajax, )
walk(document.body); //
// 2017-03-19 github require Promise ghImport
define('github-hans-ajax', ['./jquery'], function($) {
$(document).ajaxComplete(function () {
transTitle();
walk(document.body); // ajax
});
});
ghImport('github-hans-ajax')['catch'](function(e) {
setTimeout(function() { throw e });
});
/**
*
*
* @param {Element} node
*/
function walk(node) {
var nodes = node.childNodes;
for (var i = 0, len = nodes.length; i < len; i++) {
var el = nodes[i];
// todo 1. ; 2. , ;
if (el.nodeType === Node.ELEMENT_NODE) { //
//
if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') { //
if (el.type === 'button' || el.type === 'submit') {
transElement(el, 'value');
} else {
transElement(el, 'placeholder');
}
} else if (el.hasAttribute('aria-label')) { // tooltip
transElement(el, 'aria-label', true);
if (el.hasAttribute('data-copied-hint')) { //
transElement(el.dataset, 'copiedHint');
}
} else if (el.tagName === 'OPTGROUP') { // <optgroup> label
transElement(el, 'label');
}
if (el.hasAttribute('data-disable-with')) { //
transElement(el.dataset, 'disableWith');
}
// readme, ,
if (el.id !== 'readme' && !I18N.conf.reIgnore.test(el.className)) {
walk(el); //
}
} else if (el.nodeType === Node.TEXT_NODE) { //
transElement(el, 'data');
}
}
}
/**
*
*/
function getPage() {
// body class
var page = document.body.className.match(I18N.conf.rePageClass);
if (!page) { // url
page = location.href.match(I18N.conf.rePageUrl);
}
if (!page) { // pathname
page = location.pathname.match(I18N.conf.rePagePath);
}
return page ? page[1] || 'homepage' : false; // key
}
/**
*
*/
function transTitle() {
var title = translate(document.title, 'title');
if (title === false) { //
return false;
}
document.title = title;
}
/**
*
*
* @param {object} el
* @param {string} field
* @param {boolean} isAttr attr
*
* @returns {boolean}
*/
function transElement(el, field, isAttr) {
var transText = false; //
if (isAttr === undefined) { //
transText = translate(el[field], page);
} else {
transText = translate(el.getAttribute(field), page);
}
if (transText === false) { //
return false;
}
//
if (isAttr === undefined) {
el[field] = transText;
} else {
el.setAttribute(field, transText);
}
}
/**
*
*
* @param {string} text
* @param {string} page
*
* @returns {string|boolean}
*/
function translate(text, page) { //
var str;
var _key = text.trim(); // key
var _key_neat = _key
.replace(/\xa0/g, ' ') // bug
.replace(/\s{2,}/g, ' '); // ()
if (_key_neat === '') {
return false;
} //
str = transPage('pubilc', _key_neat); //
if (str !== false && str !== _key_neat) { //
str = transPage('pubilc', str) || str; //
return text.replace(_key, str); //
}
if (page === false) {
return false;
} //
str = transPage(page, _key_neat); //
if (str === false || str === '') {
return false;
} //
str = transPage('pubilc', str) || str; //
return text.replace(_key, str); //
}
/**
*
*
* @param {string} page
* @param {string} key
*
* @returns {string|boolean}
*/
function transPage(page, key) {
var str; //
var res; //
//
str = I18N[lang][page]['static'][key];
if (str) {
return str;
}
//
res = I18N[lang][page].regexp;
if (res) {
for (var i = 0, len = res.length; i < len; i++) {
str = key.replace(res[i][0], res[i][1]);
if (str !== key) {
return str;
}
}
}
return false; //
}
/**
*
*/
function timeElement() {
if (!window.RelativeTimeElement) { //
return;
}
var RelativeTimeElement$getFormattedDate = RelativeTimeElement.prototype.getFormattedDate;
var TimeAgoElement$getFormattedDate = TimeAgoElement.prototype.getFormattedDate;
// var LocalTimeElement$getFormattedDate = LocalTimeElement.prototype.getFormattedDate;
var RelativeTime = function (str, el) { //
if (/^on ([\w ]+)$/.test(str)) {
return ' ' + el.title.replace(/ .+$/, '');
}
//
var time_ago = I18N[lang].pubilc.regexp[1];
return str.replace(time_ago[0], time_ago[1]);
};
RelativeTimeElement.prototype.getFormattedDate = function () {
var str = RelativeTimeElement$getFormattedDate.call(this);
return RelativeTime(str, this);
};
TimeAgoElement.prototype.getFormattedDate = function () {
var str = TimeAgoElement$getFormattedDate.call(this);
return RelativeTime(str, this);
};
LocalTimeElement.prototype.getFormattedDate = function () {
return this.title.replace(/ .+$/, '');
};
// time
// 2016-04-16 github time
var times = document.querySelectorAll('time, relative-time, time-ago, local-time');
Array.prototype.forEach.call(times, function (el) {
if (el.getFormattedDate) { // time
el.textContent = el.getFormattedDate();
}
});
}
/**
*
*/
function contributions() {
var tip = document.getElementsByClassName('svg-tip-one-line');
// IncludeFragmentElement
// var observe = require('github/observe').observe;
define('github/hans-contributions', ['./observe'], function (observe) {
observe(".js-calendar-graph-svg", function () {
setTimeout(function () { // mouseover
var $calendar = $('.js-calendar-graph');
walk($calendar[0]); //
$calendar.on('mouseover', '.day', function () {
if (tip.length === 0) { // tip
return true;
}
var data = $(this).data(); // data
var $tip = $(tip[0]);
$tip.html(data.count + ' ' + data.date);
var rect = this.getBoundingClientRect(); //
var left = rect.left + window.pageXOffset - tip[0].offsetWidth / 2 + 5.5;
$tip.css('left', left);
});
}, 999);
});
});
ghImport('github/hans-contributions')['catch'](function(e) {
setTimeout(function() { throw e });
});
}
})(window, document);
``` | /content/code_sandbox/main.js | javascript | 2016-01-21T15:31:55 | 2024-08-16T15:12:40 | github-hans | 52cik/github-hans | 1,646 | 1,979 |
```javascript
var I18N = {};
I18N.conf = {
/**
*
*/
rePageClass: /\b(vis-public|page-(dashboard|profile|account|new-repo|create-org)|homepage|signup|session-authentication|oauth)\b/,
/**
* pathname
*
* /notifications
* /watching
* /stars
* /issues
* /pulls
* /search
* /trending
* /showcases
* /new/import
*
* /
*/
rePagePath: /\/(notifications|watching|stars|issues|search|pulls|trending|showcases|$|new\/import)/,
/**
* url
*
* gist
*/
rePageUrl: /(gist)\.github.com/,
/**
* class
*
* breadcrumb
* files js-navigation-container js-active-navigation-container
* highlight tab-size js-file-line-container
* data highlight blob-wrapper
* wiki markdown-body
*/
reIgnore: /(breadcrumb|files js-navigation-container|highlight tab-size|highlight blob-wrapper|markdown-body)/,
};
I18N.zh = {
"title": { //
"static": { //
},
"regexp": [ //
],
},
"pubilc": { //
"static": { //
//
"Personal": "",
"Open source": "",
"Business": "",
"Pricing": "",
"Support": "",
"Sign in": "",
"Sign up": "",
"Search GitHub": "GitHub ",
"This repository": "",
"Search": "",
"Pull Requests": "",
"Pull requests": "",
"Issues": "",
"Marketplace": "",
"Gist": "",
"Your dashboard": "",
"You have no unread notifications": "",
"You have unread notifications": "",
"Create new": "",
"View profile and more": "",
"New repository": "",
"New organization": "",
"Import repository": "",
"New gist": "",
"New issue": "",
"Signed in as": "",
"Your profile": "",
"Your stars": "",
"Your gists": "",
"Explore": "",
"Integrations": "",
"Help": "",
"Settings": "",
"Sign out": "",
"Showcases": "",
"Trending": "",
"Stars": "",
"Previous": "",
"Next": "",
"Period:": ":",
"Filter activity": "",
"1 day": "",
"3 days": "",
"1 week": "",
"1 month": "",
"Confirm password to continue": "",
"Password": "",
"(Forgot password)": "()",
"Confirm password": "",
"Updated": "",
"Terms": "",
"Privacy": "",
"Security": "",
"Contact": "",
"Status": "",
"Training": "",
"Shop": "",
"Blog": "",
"About": "",
//
"Write": "",
"Preview": "",
"Add header text": "",
"Add bold text <cmd+b>": " <cmd+b>",
"Add italic text <cmd+i>": " <cmd+i>",
"Insert a quote": "",
"Insert code": "",
"Add a link <cmd+k>": " <cmd+k>",
"Add a bulleted list": "",
"Add a numbered list": "",
"Add a task list": "",
"Directly mention a user or team": "",
"Reference an issue or pull request": "",
"Leave a comment": "",
"Attach files by dragging & dropping,": "",
"selecting them": "",
", or pasting from the clipboard.": "",
"Styling with Markdown is supported": " Markdown ",
"Close issue": "",
"Comment": "",
"Submit new issue": "",
"Comment on this commit": "",
"Close and comment": "",
"Reopen and comment": "",
"Reopen issue": "",
//
"Followers": "",
"Follow": "",
"Unfollow": "",
"Watch": "",
"Unwatch": "",
"Star": "",
"Unstar": "",
"Fork": "",
//
"Please verify your email address to access all of GitHub's features.": " GitHub ",
"Configure email settings": "",
"Your email was verified.": "",
},
"regexp": [ // ()
/**
*
*
* Mar 19, 2015 Mar 19, 2016
* January 26 March 19
* March 26
*
* , . 2016-03-19 20:46:45
*/
[/(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May(?:)?|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?) (\d+)(?:, (\d+)|)/g, function (all, month, date, year) {
var monthKey = {
"Jan": "1",
"Feb": "2",
"Mar": "3",
"Apr": "4",
"May": "5",
"Jun": "6",
"Jul": "7",
"Aug": "8",
"Sep": "9",
"Oct": "10",
"Nov": "11",
"Dec": "12"
};
return (year ? year + '' : '') + monthKey[month.substring(0, 3)] + date + '';
}],
/**
*
*/
[/just now|(an?|\d+) (second|minute|hour|day|month|year)s? ago/, function (m, d, t) {
if (m === 'just now') {
return '';
}
if (d[0] === 'a') {
d = '1';
} // a, an 1
var dt = {second: '', minute: '', hour: '', day: '', month: '', year: ''};
return d + ' ' + dt[t] + '';
}],
//
[/Your repository "([^"]+)"was successfully deleted\./, " \"$1\""],
//
[/An email containing verification instructions was sent to (.+)\./, " $1"],
//
[/Joined on/, ""],
],
},
"page-dashboard": { //
"static": { //
//
"Learn Git and GitHub without any code!": " Git GitHub ",
"Using the Hello World guide, youll create a repository, start a branch,": " Hello World ",
"write comments, and open a pull request.": "(...)",
"Let's get started!": "",
"Hide this notice forever": "",
"Welcome to GitHub! Whats next?": " GitHub",
"Create a repository": "",
"Tell us about yourself": "",
"Browse interesting repositories": "",
"on Twitter": " Twitter ",
"You dont have any repositories yet!": "",
"Create your first repository": "",
"or": "",
"learn more about Git and GitHub": " Git GitHub ",
//
"Repositories you contribute to": "",
"Your repositories": "",
"Find a repository": "",
"All": "",
"Public": "",
"Private": "",
"Sources": "",
"Forks": "",
"View": "",
"new broadcast": "",
"new broadcasts": "",
//
"starred": "",
"forked": "",
"forked from": "",
"created repository": "",
"opened pull request": "",
"commented on pull request": "",
"opened issue": "",
"close issue": "",
"added": "",
"to": "",
"pushed to": "",
"closed issue": "",
"merged pull request": "",
"commented on issue": "",
"More": "",
"Switch dashboard context": "",
"Manage organizations": "",
"Create organization": "",
//
"Youve been added to the": "",
"organization!": "",
"Here are some quick tips for a first-time organization member.": "",
"Use the switch context button in the upper left corner of this page to switch between your personal context (": "(",
") and organizations you are a member of.": ")",
"After you switch contexts youll see an organization-focused dashboard that lists out organization repositories and activities.": "",
},
"regexp": [ //
[/Show (\d+) more repositories/, " $1 "],
],
},
"page-profile": { //
"static": { //
"Updating your profile with your name, location, and a profile picture helps other GitHub users get to know you.": "",
"Joined on": "",
"Change your avatar": "",
"Starred": "",
"Following": "",
"Organizations": "",
"Contributions": "",
"Public contributions": "",
"Overview": "",
"Repositories": "",
"Public activity": "",
"Edit profile": "",
"Popular repositories": "",
"Pinned repositories": "",
"Customize your pinned repositories": "",
"Repositories contributed to": "",
"Contribution activity": "",
"You can now pin up to 6 repositories.": "6",
"Select up to five public repositories you'd like to show.": "",
"Show:": ":",
"Your repositories": "",
"Repositories you contribute to": "",
"Save pinned repositories": "",
"Jan": "1",
"Feb": "2",
"Mar": "3",
"Apr": "4",
"May": "5",
"Jun": "6",
"Jul": "7",
"Aug": "8",
"Sep": "9",
"Oct": "10",
"Nov": "11",
"Dec": "12",
"January": "",
"February": "",
"March": "",
"April": "",
"May": "",
"June": "",
"July": "",
"August": "",
"September": "",
"October": "",
"November": "",
"December": "",
"Mon": "",
"Wed": "",
"Fri": "",
"Includes contributions from private repositories you can access.": "",
"Summary of pull requests, issues opened, and commits.": " , , .",
"Learn how we count contributions": "",
"Less": "",
"More": "",
// "Contributions in the last year": "",
// "Longest streak": "",
// "Current streak": "",
// "No recent contributions": "",
// 2016-05-20
"Contribution settings": "",
"Select which contributions to show": "",
"Public contributions only": "",
"Visitors to your profile will only see your contributions to public repositories.": "",
"Public and private contributions": "",
"Visitors to your profile will see your public and anonymized private contributions.": "",
"Visitors will now see only your public contributions.": "",
"Visitors will now see your public and anonymized private contributions.": "",
"commits": "",
"Pull Request": "",
"Pull Requests": "",
"Issue reported": "",
"Issues reported": "",
//
"starred": "",
"forked": "",
"forked from": "",
"created repository": "",
"opened pull request": "",
"commented on pull request": "",
"opened issue": "",
"close issue": "",
"added": "",
"to": "",
"pushed to": "",
"closed issue": "",
"merged pull request": "",
"commented on issue": "",
// tab
"Find a repository": "",
"All": "",
"Public": "",
"Private": "",
"Sources": "",
"Forks": "",
"Mirrors": "",
"New": "",
"Block or report": "",
"Learn more about blocking a user.": "",
"Block or report this user": "",
"Block user": "",
"Hide content and notifications from this user.": "",
"Report abuse": "",
"Contact Support about this user's behavior.": "",
"Search repositories": "",
"Search starred repositories": "",
"Type:": ":",
"Select type:": ":",
"Language:": ":",
"Select language:": ":",
"All languages": "",
"Sort:": ":",
"Sort options": "",
"Recently starred": "",
"Recently active": "",
"Most stars": "",
"Unstar": "",
"Jump to": "",
"First pull request": "",
"First issue": "",
"First repository": "",
"Joined GitHub": " GitHub",
"Show more activity": "",
},
"regexp": [ //
[/Created (\d+)[\s\r\n]+commits? in[\s\r\n]+(\d+)[\s\r\n]+repositor(y|ies)/, " $2 $1 "],
[/Created (\d+)[\s\r\n]+repositor(y|ies)/, " $1 "],
[/Opened (\d+)[\s\r\n]+other[\s\r\n]+pull requests?/, " $1 "],
[/Opened (\d+)[\s\r\n]+other[\s\r\n]+issues/, " $1 "],
[/(\d+) commits?/, "$1 "],
[/Pushed (\d+) commits? to/, " $1 "],
[/Follow ([^]+)s activity feed/, " $1 feed"],
[/([^ ]+) has no activity during this period\./, "$1 "],
[/([\s\S]+?) has no activity yet for this period\./, "$1 "],
[/(\d+) total/, "$1 "],
[/(\d+) days?/, "$1 "],
[/([\d,]+) contributions in the last year/, "$1 "],
],
},
"page-account": { //
"static": { //
//
"Personal settings": "",
"Profile": "",
"Account": "",
"Emails": "",
"Notifications": "",
"Billing": "",
"SSH and GPG keys": "SSH GPG keys",
"Security": "",
"OAuth applications": "",
"Personal access tokens": "",
"Repositories": "",
"Organizations": "",
"Saved replies": "",
// Profile
"Public profile": "",
"Profile picture": "",
"Upload new picture": "",
"You can also drag and drop a picture from your computer.": ".",
"Name": "",
"Public email": "",
"Dont show my email address": "",
"You can add or remove verified email addresses in your": "",
"personal email settings": "",
"URL": "",
"Company": "",
"You can": "",
"other users and organizations to link to them.": "",
"Location": "",
"your company's GitHub organization to link it.": "GitHub",
"Update profile": "",
"Profile updated successfully": "",
"Contributions": "",
"Include private contributions on my profile": "",
"Get credit for all your work by showing the number of contributions to private repositories on your profile without any repository or organization information.": "",
"Learn how we count contributions": "",
"Update contributions": "",
"GitHub Developer Program": "GitHub ",
"Building an application, service, or tool that integrates with GitHub?": ",GitHub",
"Join the GitHub Developer Program": " GitHub ",
", or read more about it at our": "",
"Developer site": "",
"Jobs profile": "",
"Available for hire": "HR",
"Save jobs profile": "",
// Account settings
"Change password": "",
"Old password": "",
"New password": "",
"Confirm new password": "",
"Update password": "",
"I forgot my password": "",
"Looking for two-factor authentication? You can find it in": "",
"Change username": "",
"Changing your username can have": "",
"unintended side effects": "",
"Delete account": "",
"Once you delete your account, there is no going back. Please be certain.": "",
"Delete your account": "",
// Emails
"Your": "",
"primary GitHub email address": "GitHub Email ",
"will be used for account-related notifications (e.g. account changes and billing receipts) as well as any web-based GitHub operations (e.g. edits and merges).": " () web GitHub ()",
"Primary": "",
"Private": "",
"Public": "",
"This email will be used as the 'from' address for web-based GitHub operations.": " \"\"",
"Your primary email address is now public.": "",
"Your primary email address is now private.": "",
"Set as primary": "",
"Add email address": " Email ",
"Add": "",
"Keep my email address private": "",
"We will use": "",
"when performing web-based Git operations and sending email on your behalf. If you want command line Git operations to use your private email you must": "\"\" Git ",
"set your email in Git": "Git ",
"Email preferences": "Email ",
"Receive all emails, except those I unsubscribe from.": "",
"We'll occasionally contact you with the latest news and happenings from the GitHub Universe.": " GitHub Universe ",
"Learn more": "",
"Only receive account related emails, and those I subscribe to.": "",
"We'll only send you legal or administrative emails, and any emails youve specifically subscribed to.": "",
"Save email preferences": "",
"Successfully updated your email preferences.": "Email ",
"Looking for activity notification controls? Check the": "",
// Notification center
"How you receive notifications": "",
"Automatic watching": "",
"When youre given push access to a repository, automatically receive notifications for it.": "",
"Automatically watch repositories": "",
"Participating": "",
"When you participate in a conversation or someone brings you in with an": "",
"@mention": "@",
"Watching": "",
"Updates to any repositories or threads youre watching.": "",
"Your notification settings apply to the": "",
"repositories youre watching": "",
"Notification email": "",
"Primary email address": "",
"Save": "",
"Custom routing": "",
"You can send notifications to different": "",
"verified": "",
"email addresses depending on the organization that owns the repository.": "",
// Billing
"Billing overview": "",
"Plan": "",
"Free": "",
"Change plan": "",
"per month for": " -",
"Learn more about Git LFS": " Git LFS ()",
"Purchase more": "",
"Billing cycle": "",
"Bandwidth": "",
"Bandwidth quota resets every billing cycle": "",
"Storage": "",
"Payment": "",
"No payment method on file.": "",
"Add payment method": "",
"Coupon": "",
"You dont have an active coupon.": "",
"Redeem a coupon": "",
"Payment history": "",
"Amounts shown in USD": "",
"You have not made any payments.": "",
// Security
"Two-factor authentication": "",
"Status:": ":",
"Off": "",
"Set up two-factor authentication": "",
"provides another layer of security to your account.": "",
"Sessions": "",
"This is a list of devices that have logged into your account. Revoke any sessions that you do not recognize.": "",
"Your current session": "",
"Location:": "",
"Signed in:": "",
"Last accessed on": "",
"Revoke": "",
"Security history": "",
"This is a security log of important events involving your account.": "",
// Applications
"Authorized applications": "",
"Developer applications": "",
"Revoke all": "",
"You have granted the following applications access to your account. Read more about connecting with third-party applications at": "",
"Sort": "",
"Sort by": "",
"Alphabetical": "",
"Recently used": "",
"Least recently used": "",
"No Developer Applications": "",
"Developer applications are used to access the": "",
". To get started you should": "",
"register an application": "",
"Register new application": "",
"Register a new OAuth application": " OAuth ",
"Application name": "",
"Something users will recognize and trust": "",
"Homepage URL": "",
"The full URL to your application homepage": "",
"Application description": "",
"Application description is optional": " ()",
"This is displayed to all potential users of your application": "",
"Authorization callback URL": "",
"Your applications callback URL. Read our": "",
"OAuth documentation": "OAuth ",
"for more information": "",
"Register application": "",
"Drag & drop": "",
"or": "",
"choose an image": "",
// Personal access tokens
"Generate new token": "",
"Tokens you have generated that can be used to access the": "",
"Full control of private repositories": "",
"Edit": "",
"Delete": "",
"Personal access tokens function like ordinary OAuth access tokens. They can be used instead of a password for Git over HTTPS, or can be used to": "OAuth Git Https ",
"authenticate to the API over Basic Authentication": "API",
// Organizations
"You are not a member of any organizations.": "",
"Transform account": "",
"Account transformation warning": "",
"What you are about to do is an irreversible and destructive process. Please be aware:": "",
"Any user-specific information (OAuth tokens, SSH keys, Job Profile, etc) will be erased": "OAuth tokens, SSH keys, Job Profile, ",
"create a new personal account": "",
},
"regexp": [ //
[/This email will not be used as the 'from' address for web-based GitHub operations - we will instead use ([^@]+@users.noreply.github.com)./, " \"\" ($1) \"\""],
[/Your primary email was changed to ([^@]+@[^\n]+)\./, " Email $1"],
[/(\d+) private repositories?\./, "$1 ."],
[/(\d+) data packs?/, "$1 "],
[/(\d+) days? left,\n\s+billed monthly/, "$1, "],
[/Using\n\s+([\d.]+) of\n\s+(\d+) GB\/month/, "$1, $2GB/"],
[/Using\n\s+([\d.]+) of\n\s+(\d+) GB/, "$1, $2GB"],
[/(\d+) Authorized applications?/, "$1 "],
[/Turn (\w+) into an organization/, " $1 "],
[/You will no longer be able to sign into (\w+) \(all administrative privileges will be bestowed upon the owners you choose\)/, " $1"],
[/Any commits credited to (\w+) will no longer be linked to this GitHub account/, " $1 GitHub "],
[/If you are using (\w+) as a personal account, you should/, " $1 "],
[/before transforming (\w+) into an organization./, " $1 "],
],
},
"page-new-repo": { //
"static": { //
"Create a new repository": "",
"A repository contains all the files for your project, including the revision history.": "",
"Owner": "",
"Repository name": "",
"Great repository names are short and memorable. Need inspiration? How about": "",
"Description": "",
"(optional)": "()",
"Public": " ()",
"Anyone can see this repository. You choose who can commit.": "",
"Private": " ()",
"You choose who can see and commit to this repository.": "",
"Initialize this repository with a README": " README.md ",
"This will let you immediately clone the repository to your computer. Skip this step if youre importing an existing repository.": "",
"Add .gitignore:": " .gitignore ",
"Filter ignores": "",
"Add a license:": "",
"Filter licenses": "",
"None": "",
"Need help picking a license? Weve built a site just for you.": "",
"Create repository": "",
"Creating repository": "",
},
"regexp": [ //
],
},
"new/import": { //
"static": { //
//
"Import your project to GitHub": " GitHub",
"Import all the files, including the revision history, from another version control system.": "",
"Your old repositorys clone URL": " URL ",
"Learn more about the types of": "",
"supported VCS": " VCS",
"Your new repository details": "",
"Owner": "",
"Name": "",
"Your new repository will be": "",
"public": "",
". In order to make this repository private, youll need to": "",
"upgrade your account": "",
"Cancel": "",
"Begin import": "",
"Preparing import": "",
},
"regexp": [ //
],
},
"page-create-org": { //
"static": { //
},
"regexp": [ //
],
},
"vis-public": { //
"static": { //
//
"Preparing your new repository": "",
"There is no need to keep this window open, well email you when the import is done.": "",
"Detecting your projects version control system": "",
"Importing commits and revision history": "",
"Importing complete! Your new repository": "",
"is ready.": "",
//
"Where should we fork this repository?": "",
"Code": "",
"Pulse": "",
"Graphs": "",
"Projects": "",
//
"No description or website provided.": ".",
"Edit": "",
"Description": "",
"Short description of this repository": "",
"Website": "",
"Website for this repository (optional)": " ()",
"Save": "",
"or": "",
"Cancel": "",
//
"Notifications": "",
"Not watching": "",
"Watching": "",
"Ignoring": "",
"Be notified when participating or @mentioned.": "@.",
"Be notified of all conversations.": ".",
"Never be notified.": ".",
"commit": "",
"commits": "",
"branch": "",
"branches": "",
"release": "",
"releases": "",
"contributor": "",
"contributors": "",
"Copy to clipboard": "",
"Copied!": "!",
"Your recently pushed branches:": ":",
"(less than a minute ago)": "",
"Compare & pull request": " & ",
"New pull request": "",
"Create new file": "",
"Upload files": "",
"Find file": "",
"Copy path": "",
"Clone or download": "",
"Download ZIP": " ZIP",
"History": "",
"Use SSH": " SSH",
"Use HTTPS": " HTTPS",
"Open in Desktop": "",
"Clone with SSH": " SSH ",
"Clone with HTTPS": " HTTPS ",
"Use an SSH key and passphrase from account.": " SSH ",
"Use Git or checkout with SVN using the web URL.": " git svn ",
"Branch:": ":",
"Switch branches/tags": "",
"Branches": "",
"Tags": "",
"Nothing to show": "",
"File uploading is now available": "",
"You can now drag and drop files into your repositories.": "",
"Learn more": "",
"Dismiss": "",
//
"Watchers": "",
//
"Stargazers": "",
"All": "",
"You know": "",
// issues
"opened this": "",
"Issue": "",
"added a commit that closed this issue": "",
"closed this in": "",
"added the": "",
"added": "",
"and removed": "",
"label": "",
"labels": "",
"self-assigned this": "",
"edited": "",
"added this to the": "",
"milestone": "",
"closed this": "",
"reopened this": "",
"This was referenced": "",
"No description provided.": "",
"Add your reaction": "",
"Pick your reaction": "",
"Leave a comment": "",
"Milestone": "",
"Unsubscribe": "",
"Attach files by dragging & dropping,": "",
"selecting them": "",
", or pasting from the clipboard.": "",
"Styling with Markdown is supported": " Markdown ",
"Close issue": "",
"Comment": "",
"Filters": "",
"Open issues and pull requests": "",
"Your issues": "",
"Your pull requests": "",
"Everything assigned to you": "",
"Everything mentioning you": "",
"View advanced search syntax": "",
"Labels": "",
"None yet": "",
"Milestones": "",
"No milestone": "",
"Author": "",
"Assignee": "",
"Assignees": "",
"No one": " - ",
"assign yourself": " ",
"No one assigned": "",
"Sort": "",
"Filter by author": "",
"Filter users": "",
"Filter by label": "",
"Filter labels": "",
"Unlabeled": "",
"Filter by milestone": "",
"Filter milestones": "",
"Issues with no milestone": "",
"Filter by whos assigned": "",
"Assigned to nobody": "",
"Sort by": "",
"Newest": "",
"Oldest": "",
"Most commented": "",
"Least commented": "",
"Recently updated": "",
"Least recently updated": "",
"View all issues in this milestone": "",
// New collaborator
"New collaborator": "",
"Collaborators": "",
"Push access to the repository": "",
"This repository doesnt have any collaborators yet. Use the form below to add a collaborator.": "",
"Search by username, full name or email address": ", , ",
"Add collaborator": "",
// Upload files
"Drag files here to add them to your repository": "",
"Drag additional files here to add them to your repository": "",
"Drop to upload your files": "",
"Or": "",
"choose your files": "",
"Yowza, thats a big file. Try again with a file smaller than 25MB.": "25MB",
"Yowza, thats a lot of files. Try again with fewer than 100 files.": "100",
"This file is empty.": "",
"Something went really wrong, and we cant process that file.": "",
"Uploading": "",
"of": "",
"files": "",
"Commit changes": "",
"Add files via upload": "",
"Optional extended description": "",
"Add an optional extended description": "... ()",
"Commit directly to the": "",
"Create a": "",
"new branch": "",
"for this commit and start a pull request.": "",
"Learn more about pull requests.": "",
// Find file
"Youve activated the": "",
"file finder": "",
". Start typing to filter the file list. Use": "",
"and": "",
"to navigate,": "",
"to view files,": "",
"to exit.": "",
//
"Your recently pushed branches:": ":",
"Compare & pull request": " & ",
// Pull Requests
"There arent any open pull requests.": "",
"There arent any open issues.": "",
"Use the links above to find what youre looking for, or try": "",
"a new search query": "",
". The Filters menu is also super helpful for quickly finding issues most relevant to you.": "",
"Conversation": "",
"Files changed": "",
"commented": "",
"merged commit": "",
"into": "",
"from": "",
"Revert": "",
"Avoid bugs by automatically running your tests.": "BUG",
"Continuous integration can help catch bugs by running your tests automatically.": "",
"Merge your code with confidence using one of our continuous integration providers.": "",
"Add more commits by pushing to the": "",
"branch on": "",
"This branch has no conflicts with the base branch": "base",
"Merging can be performed automatically.": "",
"You can also": "",
"open this in GitHub Desktop": "GitHub",
"or view": "",
"command line instructions": "",
////
"Open a pull request": "",
"Create a new pull request by comparing changes across two branches. If you need to, you can also": "",
"Able to merge.": "",
"These branches can be automatically merged.": "",
"file changed": "",
"files changed": "",
"commit comment": "",
"commit comments": "",
"No commit comments for this range": "",
"Comparing changes": "",
"Choose two branches to see whats changed or to start a new pull request. If you need to, you can also": "",
"base fork:": ":",
"There isnt anything to compare.": "",
"is up to date with all commits from": "",
". Try": "",
"switching the base": "",
"for your comparison.": "",
// projects
"This repository doesn't have any projects yet": "",
"Create a project": "",
// wiki
"Wikis provide a place in your repository to lay out the roadmap of your project, show the current status, and document software better, together.": "wiki ",
"Create the first page": "",
"Create new page": "",
"Write": "",
"Preview": "",
"Edit mode:": ":",
"Edit Message": "",
"Save Page": "",
// settings
"Webhooks & services": "Web & ",
"Deploy keys": "",
"Options": "",
"Repository name": "",
"Rename": "",
"Features": "",
"GitHub Wikis is a simple way to let others contribute content. Any GitHub user can create and edit pages to use for documentation, examples, support, or anything you wish.": "GitHub Wikis GitHub ",
"Restrict editing to collaborators only": "",
"Public wikis will still be readable by everyone.": " wikis ",
"GitHub Issues adds lightweight issue tracking tightly integrated with your repository. Add issues to milestones, label issues, and close & reference issues from commit messages.": "GitHub ",
"Merge button": "",
"When merging pull requests, you can allow merge commits, squashing, or both.": "",
"Allow merge commits": "",
"Add all commits from the head branch to the base branch with a merge commit.": "headbase",
"Allow squash merging": "",
"Combine all commits from the head branch into a single commit in the base branch.": "headbase",
"You must select at least one option": "",
"GitHub Pages": "GitHub ",
"Your site is published at": ":",
"Your site is ready to be published at": ":",
"is designed to host your personal, organization, or project pages from a GitHub repository.": "web",
"Source": "",
"Your GitHub Pages site is currently being built from the": " GitHub Pages ",
"branch.": "",
"Select source": "",
"Use the": "",
"branch for GitHub Pages.": " GitHub Pages",
"Disable GitHub Pages.": " GitHub Pages",
"Custom domain": "",
"Custom domains allow you to serve your site from a domain other than": "",
"Update your site": "",
"To update your site, push your HTML or": " html ",
"updates to your": "",
"branch. Read the": "",
"Pages help article": "",
"for more information.": "",
"Overwrite site": "",
"Replace your existing site by using our automatic page generator. Author your content in our Markdown editor, select a theme, then publish.": " Markdown ",
"Launch automatic page generator": "",
"Enforce HTTPS": " HTTPS",
" Unavailable for your site because you have a custom domain configured (": "- (",
"HTTPS provides a layer of encryption that prevents others from snooping on or tampering with traffic to your site.": "HTTPS ",
"When HTTPS is enforced, your site will only be served over HTTPS.": " HTTPS HTTPS ",
"Danger Zone": "",
"Make this repository private": "",
"Public forks cant be made private. Please": "",
"duplicate the repository": "",
"Make private": "",
"Please": "",
"upgrade your plan": "",
"to make this repository private.": "",
"Transfer ownership": "",
"Transfer": "",
"Transfer this repository to another user or to an organization where you have admin rights.": "",
"Delete this repository": "",
"Once you delete a repository, there is no going back. Please be certain.": "",
"Default branch": "",
"The default branch is considered the base branch in your repository, against which all pull requests and code commits are automatically made, unless you specify a different branch.": "",
"Update": "",
"Switch default branch": "",
"Filter branches": "",
"Protected branches": "",
"Protect branches to disable force pushing, prevent branches from being deleted, and optionally require status checks before merging. New to protected branches?": "",
"Learn more.": "",
"No protected branches yet.": "",
"Are you ABSOLUTELY sure?": "",
"Unexpected bad things will happen if you dont read this!": "",
"This action": "",
"CANNOT": "",
"be undone. This will permanently delete the": "",
"repository, wiki, issues, and comments, and remove all collaborator associations.": "wiki",
"Please type in the name of the repository to confirm.": "",
"I understand the consequences, delete this repository": "",
// Compare changes
"Compare changes": "",
"Compare changes across branches, commits, tags, and more below. If you need to, you can also": "",
"compare across forks": "",
"base:": ":",
"compare:": ":",
"Create pull request": "",
"Choose different branches or forks above to discuss and review changes.": "",
"Compare and review just about anything": "",
"Branches, tags, commit ranges, and time ranges. In the same repository and across forks.": "",
"Example comparisons": "",
//
"Quick setup": "",
" if youve done this kind of thing before": "- ",
"Set up in Desktop": "",
"We recommend every repository include a": "",
", and": "",
"or create a new repository on the command line": "",
"or push an existing repository from the command line": "",
"or import code from another repository": "",
"You can initialize this repository with code from a Subversion, Mercurial, or TFS project.": " SubversionMercurial TFS ",
"Import code": "",
// commits
"committed": "",
"Merge pull request": "",
"Confirm merge": "",
"Close pull request": "",
"Copy the full SHA": " SHA",
"Browse the repository at this point in the history": "",
"Newer": "",
"Older": "",
// branches
"Overview": "",
"Yours": "",
"Active": "",
"Stale": "",
"All branches": "",
"Search branches": "",
"Your branches": "",
"You havent pushed any branches to this repository.": "",
"Active branches": "",
"There arent any active branches.": "",
"Stale branches": "",
"There arent any stale branches.": "",
"View more active branches": "",
"View more stale branches": "",
"Compare": "",
"Change default branch": "",
// Releases
"Releases": "",
"Pre-release": "",
"Downloads": "",
"Notes": "",
"There arent any releases here": "",
"Create a new release": "",
"Releases are powered by": "",
"tagging specific points of history": "",
"in a repository. Theyre great for marking release points like": "",
"Latest release": "",
"Read release notes": "",
"released this": "",
"tagged this": "",
"Draft a new release": "",
"Add release notes": "",
"Edit release notes": "",
"(No release notes)": "()",
"Release notes": "",
"Edit tag": "",
"Edit release": "",
"Delete": "",
"Are you sure?": "",
"This will delete the information for this tag.": "",
"Delete this tag": "",
"Your tag was removed": "",
"Existing tag": "",
"Markdown supported": "Markdown ",
"Attach binaries by dropping them here or": "",
"This is a pre-release": "",
"Well point out that this release is identified as non-production ready.": "",
"Update release": "",
"Publish release": "",
"Save draft": "",
"Saved!": "",
"Saving draft failed. Try again?": "",
//
"Contributors": "",
"Traffic": "",
"Commits": "",
"Code frequency": "",
"Punch card": "",
"Network": "",
"Members": "",
"Contributions to master, excluding merge commits": "",
"Contributions:": ":",
"Filter contributions": "",
"Additions": "",
"Deletions": "",
},
"regexp": [ //
[/HTTPS\s+(recommended)/, "HTTPS ()"],
[/Save (.+?) to your computer and use it in GitHub Desktop./, " GitHub $1 "],
[/([\d,]+) Open/, "$1 "],
[/([\d,]+) Closed/, "$1 "],
[/View all issues opened by (.+)/, " $1 "],
[/Welcome to the ([^ ]+) wiki!/, " $1 wiki"],
[/([\d,]+) participants?/, "$1 "],
[/Commits on (.+)/, " $1"],
// bug [/from (.+)/, " $1"],
[/wants to merge ([\d,]+) commits? into/, " $1 "],
[/([\d,]+) commits?/, "$1 "],
[/to ([^\n]+)[\n\s]+since this release/, " $1 "],
[/ ([\d,]+) comments?/, "$1 "]
],
},
"homepage": { //
"static": { //
"Pick a username": "",
"Your email address": "",
"Create a password": "",
"Sign up for GitHub": " GitHub",
"Use at least one letter, one numeral, and seven characters.": " 7 ",
"By clicking \"Sign up for GitHub\", you agree to our": " GitHub",
"terms of service": "",
"and": "",
"privacy policy": "",
"We'll occasionally send you account related emails.": "",
"How people build software": "",
"Millions of developers use GitHub to build personal projects, support their businesses, and work together on open source technologies.": " GitHub ",
"Introducing unlimited": "",
"private repositories": "",
"All of our paid plans on GitHub.com now include unlimited private repositories.": " GitHub.com ",
"Sign up": "",
"to get started or": "",
"read more about this change on our blog": "",
"Welcome home, developers": "",
"GitHub fosters a fast, flexible, and collaborative development process that lets you work on your own or with others.": "GitHub ",
"For everything you build": "",
"Host and manage your code on GitHub. You can keep your work private or share it with the world.": " GitHub ",
"A better way to work": "",
"From hobbyists to professionals, GitHub helps developers simplify the way they build software.": "GitHub ",
"Millions of projects": "",
"GitHub is home to millions of open source projects. Try one out or get inspired to create your own.": "GitHub ",
"One platform, from start to finish": "",
"With hundreds of integrations, GitHub is flexible enough to be at the center of your development process.": "GitHub ",
"Who uses GitHub?": " GitHub ?",
"Individuals": "",
"Use GitHub to create a personal project, whether you want to experiment with a new programming language or host your lifes work.": " GitHub ",
"Communities": "",
"GitHub hosts one of the largest collections of open source software. Create, manage, and work on some of todays most influential technologies.": "GitHub ",
"Businesses": "",
"Businesses of all sizes use GitHub to support their development process and securely build software.": " GitHub ",
"GitHub is proud to host projects and organizations like": "GitHub ",
"Public projects are always free. Work together across unlimited private repositories for $7 / month.": " 7 ",
},
"regexp": [ //
],
},
"session-authentication": { //
"static": { //
"Sign in to GitHub": " GitHub ",
"Username or email address": "/",
"Password": "",
"Forgot password?": "",
"Sign in": "",
"New to GitHub?": " GitHub?",
"Create an account": "",
},
"regexp": [ //
],
},
"signup": { //
"static": { //
"Join GitHub": " GitHub",
"The best way to design, build, and ship software.": "",
"Step 1:": ":",
"Set up a personal account": "",
"Step 2:": ":",
"Choose your plan": "",
"Step 3:": ":",
"Go to your dashboard": "",
// Step 1:
"Create your personal account": "",
"Username": " ()",
"This will be your username you can enter your organizations username next.": " - ",
"Email Address": "Email ",
"You will occasionally receive account related emails. We promise not to share your email with anyone.": "",
"Password": "",
"Use at least one lowercase letter, one numeral, and seven characters.": " 7 ",
"By clicking on \"Create an account\" below, you are agreeing to the": "",
"Terms of Service": "",
"and the": "",
"Privacy Policy": "",
"Create an account": "",
"Youll love GitHub": " GitHub",
"Unlimited": "",
"collaborators": "",
"public repositories": "",
"Great communication": "",
"Friction-less development": "",
"Open source community": "",
// Step 2:
"Welcome to GitHub": " GitHub",
"Youve taken your first step into a larger world,": "",
"Choose your personal plan": "",
"Unlimited public repositories for free.": "",
"Unlimited private repositories": "",
"for": "",
"$7/month.": "$7/",
"46.06/month.": "46.06/.",
"(view in CNY)": "()",
"(view in USD)": "()",
"Dont worry, you can cancel or upgrade at any time.": "",
"Charges to your account will be made in ": "...",
"Secure": "",
"Enter your billing details": "",
"Pay with": "",
"Credit card": "",
"PayPal account": "PayPal ",
"Credit card number": "",
"Accepted cards": "",
"Help me set up an organization next": "",
"Organizations are separate from personal accounts and are best suited for businesses who need to manage permissions for many employees.": "",
"Learn more about organizations.": "",
"Finish sign up": "",
"Both plans include:": "",
"Collaborative code review": "",
"Issue tracking": "",
"Unlimited public repositories": "",
"Join any organization": "",
},
"regexp": [ //
],
},
"notifications": { //
"static": { //
"Mark all as read": "",
"Are you sure?": "",
"Are you sure you want to mark all unread notifications as read?": "",
"Mark all notifications as read": "",
"Notifications": "",
"Watching": "",
"Unread": "",
"Participating": "",
"All notifications": "",
"No new notifications.": "",
"Depending on": "",
"your notification settings": "",
", youll see updates here for your conversations in watched repositories.": "",
},
"regexp": [ //
],
},
"watching": { //
"static": { //
"Notifications": "",
"Watching": "",
"Watched repositories": "",
"Sorted by most recently watched.": "",
"Unwatch all": "",
"Notification settings": "",
"You can change how you receive notifications from your account settings.": "",
"Change notification settings": "",
},
"regexp": [ //
],
},
"stars": { //
"static": { //
"All stars": "",
"Your repositories": "",
"Others' repositories": "",
"Filter by languages": "",
"Jump to a friend": "",
},
"regexp": [ //
],
},
"trending": { //
"static": { //
"Trending in open source": "",
"See what the GitHub community is most excited about today.": " GitHub ",
"See what the GitHub community is most excited about this week.": " GitHub ",
"See what the GitHub community is most excited about this month.": " GitHub ",
"Trending developers": "",
"These are the organizations and developers building the hot tools today.": "",
"These are the organizations and developers building the hot tools this week.": "",
"These are the organizations and developers building the hot tools this month.": "",
"Repositories": "",
"Developers": "",
"Trending:": ":",
"Adjust time span": "",
"today": "",
"this week": "",
"this month": "",
"All languages": "",
"Unknown languages": "",
"Other:": ":",
"Languages": "",
"Other Languages": "",
"Filter Languages": "",
},
"regexp": [ //
[/([\d,]+) stars today([^B]+)[\w ]+/, " $1 $2"],
[/([\d,]+) stars this week([^B]+)[\w ]+/, " $1 $2"],
[/([\d,]+) stars this month([^B]+)[\w ]+/, " $1 $2"],
],
},
"showcases": { //
"static": { //
"Open source showcases": "",
"Browse popular repositories based on the topic that interests you most.": "",
"Search showcases": "",
},
},
"issues": { //
"static": { //
"Created": "",
"Assigned": "",
"Mentioned": "",
"Visibility": "",
"Repository visibility": "",
"Private repositories only": "",
"Public repositories only": "",
"Organization": "",
"Filter by organization or owner": "",
"Filter organizations": "",
"Sort": "",
"Sort by": "",
"Newest": "",
"Oldest": "",
"Most commented": "",
"Least commented": "",
"Recently updated": "",
"Least recently updated": "",
"Most reactions": "",
"No results matched your search.": "",
"Use the links above to find what youre looking for, or try": "",
"a new search query": "",
". The Filters menu is also super helpful for quickly finding issues most relevant to you.": "",
"ProTip!": "",
"Updated in the last three days": "",
},
"regexp": [ //
[/(\d+) Open/, "$1 "],
[/(\d+) Closed/, "$1 "],
],
},
"search": { //
"static": { //
"Search more than": "",
"repositories": "",
"Repositories": "",
"Code": "",
"Users": "",
"Languages": "",
"Advanced search": "",
"Cheat sheet": "",
"You could try an": "",
"advanced search": "",
"Sort:": ":",
"Sort options": "",
"Best match": "",
"Most stars": "",
"Fewest stars": "",
"Most forks": "",
"Fewest forks": "",
"Recently updated": "",
"Least recently updated": "",
//
"Advanced options": "",
"From these owners": "",
"In these repositories": "",
"Created on the dates": "",
"Written in this language": "",
"Any Language": "",
"Popular": "",
"Everything else": "",
"Repositories options": "",
"With this many stars": "",
"With this many forks": "",
"Of this size": "",
"Pushed to": "",
"Return repositories": "",
"not": "",
"and": "",
"only": "",
"including forks.": "",
"Code options": "",
"With this extension": "",
"Of this file size": "",
"In this path": "",
"Return code from forked repositories": "",
"Issues options": "",
"In the state": "",
"With this many comments": "",
"With the labels": "",
"Opened by the author": "",
"Mentioning the users": "",
"Assigned to the users": "",
"Updated before the date": "",
"Users options": "",
"With this full name": "",
"From this location": "",
"With this many followers": "",
"With this many public repositories": "",
"Working in this language": "",
},
"regexp": [ //
[/Weve found ([\d,]+) repository results/, " $1 "],
[/We couldnt find any repositories matching '(.+)'/, " '$1' "],
],
},
"gist": { //
"static": { //
"Search": "",
"All gists": "",
"New gist": "",
"Your gists": "",
"Starred gists": "",
"Your GitHub profile": "",
"View profile and more": "",
"See all of your gists": "",
"Instantly share code, notes, and snippets.": "",
"Gist description": "",
"Filename including extension": " ()",
"Indent mode": "",
"Spaces": "",
"Tabs": "TAB",
"Indent size": "",
"Line wrap mode": "",
"No wrap": "",
"Soft wrap": "",
"Add file": "",
"Create secret gist": "",
"Secret gists are hidden from search engines but visible to anyone you give the URL.": " url ",
"Create public gist": "",
// All gists
"Sort:": ":",
"Sort options": "",
"Recently created": "",
"Least recently created": "",
"Recently updated": "",
"Least recently updated": "",
"Filter:": ":",
"Filter options": "",
"Public & Secret": " & ",
"Public only": "",
"Secret only": "",
"forked from": "",
"Created": "",
"View": "",
"Newer": "",
"Older": "",
// View
"Edit": "",
"Delete": "",
"Star": "",
"Unstar": "",
"User actions": "",
"Report abuse": "",
"Code": "",
"Revisions": "",
"Stars": "",
"Forks": "",
//
"What would you like to do?": "",
"Embed this gist in your website.": "Embed ",
"Copy sharable URL for this gist.": " URL ",
"Clone with Git or checkout with SVN using the repository's web address.": "Git SVN web ",
"Clone with an SSH key and passphrase from your GitHub settings.": " SSH ",
"Learn more about clone URLs": "",
"Copy to clipboard": "",
"Copied!": "!",
"Download ZIP": " ZIP",
"Permalink": "",
"Raw": "",
//
"Unified": "",
"Split": "",
"created": "",
"this gist": "",
//
"Editing": "",
"Make secret": "",
"Cancel": "",
"Update public gist": "",
//
"Starred": "",
"You dont have any starred gists yet.": "",
},
"regexp": [ //
[/View ([^ ]+) on GitHub/, " $1 GitHub"],
[/(\d+) files?/, "$1 "],
[/(\d+) forks?/, "$1 "],
[/(\d+) comments?/, "$1 "],
[/(\d+) stars?/, "$1 "],
[/Save (.+?) to your computer and use it in GitHub Desktop./, " GitHub $1 "],
],
},
"oauth": { //
"static": { //
"Authorize application": "",
"by": "",
"would like permission to access your account": "",
"Review permissions": "",
"Public data only": "",
"Limited access to your public data": "",
"This application will be able to identify you and read public information.": "",
"Learn more": "",
"Visit applications website": "",
"Learn more about OAuth": "",
},
"regexp": [ //
],
},
};
//
I18N.zh.pulls = I18N.zh.issues;
``` | /content/code_sandbox/locals.js | javascript | 2016-01-21T15:31:55 | 2024-08-16T15:12:40 | github-hans | 52cik/github-hans | 1,646 | 12,817 |
```ruby
#
# Be sure to run `pod lib lint Pulley.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see path_to_url
#
Pod::Spec.new do |s|
s.name = 'Pulley'
s.version = ENV['LIB_VERSION'] || '2.9.0'
s.summary = 'A library to imitate the iOS 10 Maps UI.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
A library to provide a drawer controller that can imitate the drawer UI in iOS 10's Maps app.
DESC
s.homepage = 'path_to_url
s.screenshots = 'path_to_url
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Brendan Lee' => 'brendan@52inc.com' }
s.source = { :git => 'path_to_url :tag => s.version.to_s }
s.social_media_url = 'path_to_url
s.ios.deployment_target = '9.0'
s.swift_version = '5.0'
s.source_files = 'PulleyLib/*.{h,swift}'
# s.public_header_files = 'Pod/Classes/**/*.h'
s.frameworks = 'UIKit'
end
``` | /content/code_sandbox/Pulley.podspec | ruby | 2016-07-08T21:57:00 | 2024-08-10T19:44:06 | Pulley | 52inc/Pulley | 2,009 | 390 |
```swift
// swift-tools-version:5.0
//
// Package.swift
//
//
// 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.
//
import PackageDescription
let package = Package(
name: "Pulley",
platforms: [.iOS(.v9)],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "Pulley",
targets: ["Pulley"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(name: "Pulley",
path: "PulleyLib")
]
)
``` | /content/code_sandbox/Package.swift | swift | 2016-07-08T21:57:00 | 2024-08-10T19:44:06 | Pulley | 52inc/Pulley | 2,009 | 436 |
```swift
//
// PulleyPassthroughScrollView.swift
// Pulley
//
// Created by Brendan Lee on 7/6/16.
//
import UIKit
protocol PulleyPassthroughScrollViewDelegate: AnyObject {
func shouldTouchPassthroughScrollView(scrollView: PulleyPassthroughScrollView, point: CGPoint) -> Bool
func viewToReceiveTouch(scrollView: PulleyPassthroughScrollView, point: CGPoint) -> UIView
}
class PulleyPassthroughScrollView: UIScrollView {
weak var touchDelegate: PulleyPassthroughScrollViewDelegate?
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if
let touchDelegate = touchDelegate,
touchDelegate.shouldTouchPassthroughScrollView(scrollView: self, point: point)
{
return touchDelegate.viewToReceiveTouch(scrollView: self, point: point).hitTest(touchDelegate.viewToReceiveTouch(scrollView: self, point: point).convert(point, from: self), with: event)
}
return super.hitTest(point, with: event)
}
}
``` | /content/code_sandbox/PulleyLib/PulleyPassthroughScrollView.swift | swift | 2016-07-08T21:57:00 | 2024-08-10T19:44:06 | Pulley | 52inc/Pulley | 2,009 | 229 |
```swift
//
// UIView+constrainToParent.swift
// Pulley
//
// Created by Mathew Polzin on 8/22/17.
//
import UIKit
extension UIView {
func constrainToParent() {
constrainToParent(insets: .zero)
}
func constrainToParent(insets: UIEdgeInsets) {
guard let parent = superview else { return }
translatesAutoresizingMaskIntoConstraints = false
let metrics: [String : Any] = ["left" : insets.left, "right" : insets.right, "top" : insets.top, "bottom" : insets.bottom]
parent.addConstraints(["H:|-(left)-[view]-(right)-|", "V:|-(top)-[view]-(bottom)-|"].flatMap {
NSLayoutConstraint.constraints(withVisualFormat: $0, metrics: metrics, views: ["view": self])
})
}
}
``` | /content/code_sandbox/PulleyLib/UIView+constrainToParent.swift | swift | 2016-07-08T21:57:00 | 2024-08-10T19:44:06 | Pulley | 52inc/Pulley | 2,009 | 190 |
```swift
//
// UIViewController+PulleyViewController.swift
// Pulley
//
// Created by Guilherme Souza on 4/28/18.
//
import UIKit
public extension UIViewController {
/// If this viewController pertences to a PulleyViewController, return it.
var pulleyViewController: PulleyViewController? {
var parentVC = parent
while parentVC != nil {
if let pulleyViewController = parentVC as? PulleyViewController {
return pulleyViewController
}
parentVC = parentVC?.parent
}
return nil
}
}
``` | /content/code_sandbox/PulleyLib/UIViewController+PulleyViewController.swift | swift | 2016-07-08T21:57:00 | 2024-08-10T19:44:06 | Pulley | 52inc/Pulley | 2,009 | 125 |
```swift
//
// PrimaryTransitionTargetViewController.swift
// Pulley
//
// Created by Brendan Lee on 7/8/16.
//
import UIKit
import Pulley
class PrimaryTransitionTargetViewController: UIViewController {
@IBAction func goBackButtonPressed(sender: AnyObject) {
// Uncomment the bellow code to create a secondary drawer content view controller
// and set it's initial position with setDrawerContentViewController(controller, position, animated, completion)
/*
let drawerContent = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SecondaryDrawerContentViewController")
self.pulleyViewController?.setDrawerContentViewController(controller: drawerContent, position: .open, animated: true, completion: nil)
*/
let primaryContent = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PrimaryContentViewController")
self.pulleyViewController?.setPrimaryContentViewController(controller: primaryContent, animated: true)
}
}
``` | /content/code_sandbox/Pulley/PrimaryTransitionTargetViewController.swift | swift | 2016-07-08T21:57:00 | 2024-08-10T19:44:06 | Pulley | 52inc/Pulley | 2,009 | 203 |
```swift
//
// DrawerPreviewContentViewController.swift
// Pulley
//
// Created by Brendan Lee on 7/6/16.
//
import UIKit
import Pulley
class DrawerContentViewController: UIViewController {
// Pulley can apply a custom mask to the panel drawer. This variable toggles an example.
private var shouldDisplayCustomMaskExample = false
@IBOutlet var tableView: UITableView!
@IBOutlet var searchBar: UISearchBar!
@IBOutlet var gripperView: UIView!
@IBOutlet var topSeparatorView: UIView!
@IBOutlet var bottomSeperatorView: UIView!
@IBOutlet var gripperTopConstraint: NSLayoutConstraint!
// We adjust our 'header' based on the bottom safe area using this constraint
@IBOutlet var headerSectionHeightConstraint: NSLayoutConstraint!
fileprivate var drawerBottomSafeArea: CGFloat = 0.0 {
didSet {
self.loadViewIfNeeded()
// We'll configure our UI to respect the safe area. In our small demo app, we just want to adjust the contentInset for the tableview.
tableView.contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: drawerBottomSafeArea, right: 0.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
gripperView.layer.cornerRadius = 2.5
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// You must wait until viewWillAppear -or- later in the view controller lifecycle in order to get a reference to Pulley via self.parent for customization.
// UIFeedbackGenerator is only available iOS 10+. Since Pulley works back to iOS 9, the .feedbackGenerator property is "Any" and managed internally as a feedback generator.
if #available(iOS 10.0, *)
{
let feedbackGenerator = UISelectionFeedbackGenerator()
self.pulleyViewController?.feedbackGenerator = feedbackGenerator
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if shouldDisplayCustomMaskExample {
let maskLayer = CAShapeLayer()
maskLayer.path = CustomMaskExample().customMask(for: view.bounds).cgPath
view.layer.mask = maskLayer
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// The bounce here is optional, but it's done automatically after appearance as a demonstration.
Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(bounceDrawer), userInfo: nil, repeats: false)
}
@objc fileprivate func bounceDrawer() {
// We can 'bounce' the drawer to show users that the drawer needs their attention. There are optional parameters you can pass this method to control the bounce height and speed.
self.pulleyViewController?.bounceDrawer()
}
}
extension DrawerContentViewController: PulleyDrawerViewControllerDelegate {
func collapsedDrawerHeight(bottomSafeArea: CGFloat) -> CGFloat
{
// For devices with a bottom safe area, we want to make our drawer taller. Your implementation may not want to do that. In that case, disregard the bottomSafeArea value.
return 68.0 + (pulleyViewController?.currentDisplayMode == .drawer ? bottomSafeArea : 0.0)
}
func partialRevealDrawerHeight(bottomSafeArea: CGFloat) -> CGFloat
{
// For devices with a bottom safe area, we want to make our drawer taller. Your implementation may not want to do that. In that case, disregard the bottomSafeArea value.
return 264.0 + (pulleyViewController?.currentDisplayMode == .drawer ? bottomSafeArea : 0.0)
}
func supportedDrawerPositions() -> [PulleyPosition] {
return PulleyPosition.all // You can specify the drawer positions you support. This is the same as: [.open, .partiallyRevealed, .collapsed, .closed]
}
// This function is called by Pulley anytime the size, drawer position, etc. changes. It's best to customize your VC UI based on the bottomSafeArea here (if needed). Note: You might also find the `pulleySafeAreaInsets` property on Pulley useful to get Pulley's current safe area insets in a backwards compatible (with iOS < 11) way. If you need this information for use in your layout, you can also access it directly by using `drawerDistanceFromBottom` at any time.
func drawerPositionDidChange(drawer: PulleyViewController, bottomSafeArea: CGFloat)
{
// We want to know about the safe area to customize our UI. Our UI customization logic is in the didSet for this variable.
drawerBottomSafeArea = bottomSafeArea
/*
Some explanation for what is happening here:
1. Our drawer UI needs some customization to look 'correct' on devices like the iPhone X, with a bottom safe area inset.
2. We only need this when it's in the 'collapsed' position, so we'll add some safe area when it's collapsed and remove it when it's not.
3. These changes are captured in an animation block (when necessary) by Pulley, so these changes will be animated along-side the drawer automatically.
*/
if drawer.drawerPosition == .collapsed
{
headerSectionHeightConstraint.constant = 68.0 + drawerBottomSafeArea
}
else
{
headerSectionHeightConstraint.constant = 68.0
}
// Handle tableview scrolling / searchbar editing
tableView.isScrollEnabled = drawer.drawerPosition == .open || drawer.currentDisplayMode == .panel
if drawer.drawerPosition != .open
{
searchBar.resignFirstResponder()
}
if drawer.currentDisplayMode == .panel
{
topSeparatorView.isHidden = drawer.drawerPosition == .collapsed
bottomSeperatorView.isHidden = drawer.drawerPosition == .collapsed
}
else
{
topSeparatorView.isHidden = false
bottomSeperatorView.isHidden = true
}
}
/// This function is called when the current drawer display mode changes. Make UI customizations here.
func drawerDisplayModeDidChange(drawer: PulleyViewController) {
print("Drawer: \(drawer.currentDisplayMode)")
gripperTopConstraint.isActive = (drawer.currentDisplayMode == .drawer || drawer.currentDisplayMode == .compact)
}
}
extension DrawerContentViewController: UISearchBarDelegate {
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
pulleyViewController?.setDrawerPosition(position: .open, animated: true)
}
}
extension DrawerContentViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "SampleCell", for: indexPath)
}
}
extension DrawerContentViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 81.0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let primaryContent = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PrimaryTransitionTargetViewController")
pulleyViewController?.setDrawerPosition(position: .collapsed, animated: true)
pulleyViewController?.setPrimaryContentViewController(controller: primaryContent, animated: false)
}
}
``` | /content/code_sandbox/Pulley/DrawerContentViewController.swift | swift | 2016-07-08T21:57:00 | 2024-08-10T19:44:06 | Pulley | 52inc/Pulley | 2,009 | 1,621 |
```swift
//
// ViewController.swift
// Pulley
//
// Created by Brendan Lee on 7/6/16.
//
import UIKit
import MapKit
import Pulley
class PrimaryContentViewController: UIViewController {
@IBOutlet var mapView: MKMapView!
@IBOutlet var controlsContainer: UIView!
@IBOutlet var temperatureLabel: UILabel!
/**
* IMPORTANT! If you have constraints that you use to 'follow' the drawer (like the temperature label in the demo)...
* Make sure you constraint them to the bottom of the superview and NOT the superview's bottom margin. Double click the constraint, and you can change it in the dropdown in the right-side panel. If you don't, you'll have varying spacings to the drawer depending on the device.
*/
@IBOutlet var temperatureLabelBottomConstraint: NSLayoutConstraint!
fileprivate let temperatureLabelBottomDistance: CGFloat = 8.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
controlsContainer.layer.cornerRadius = 10.0
temperatureLabel.layer.cornerRadius = 7.0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Customize Pulley in viewWillAppear, as the view controller's viewDidLoad will run *before* Pulley's and some changes may be overwritten.
// Uncomment if you want to change the visual effect style to dark. Note: The rest of the sample app's UI isn't made for dark theme. This just shows you how to do it.
// drawer.drawerBackgroundVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
// We want the 'side panel' layout in landscape iPhone / iPad, so we set this to 'automatic'. The default is 'bottomDrawer' for compatibility with older Pulley versions.
self.pulleyViewController?.displayMode = .automatic
}
@IBAction func runPrimaryContentTransitionWithoutAnimation(sender: AnyObject) {
let primaryContent = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PrimaryTransitionTargetViewController")
self.pulleyViewController?.setPrimaryContentViewController(controller: primaryContent, animated: false)
}
@IBAction func runPrimaryContentTransition(sender: AnyObject) {
let primaryContent = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PrimaryTransitionTargetViewController")
self.pulleyViewController?.setPrimaryContentViewController(controller: primaryContent, animated: true)
}
}
extension PrimaryContentViewController: PulleyPrimaryContentControllerDelegate {
func makeUIAdjustmentsForFullscreen(progress: CGFloat, bottomSafeArea: CGFloat)
{
guard let drawer = self.pulleyViewController, drawer.currentDisplayMode == .drawer else {
controlsContainer.alpha = 1.0
return
}
controlsContainer.alpha = 1.0 - progress
}
func drawerChangedDistanceFromBottom(drawer: PulleyViewController, distance: CGFloat, bottomSafeArea: CGFloat)
{
// As of iOS 14, setting the constant on the constraint causes viewDidLayoutSubviews() to be call
// on the PulleyViewController. This was causing issues with the drawer scroll view in 2.8.2+, see fix
// for issue #400 and update 2.8.5
guard drawer.currentDisplayMode == .drawer else {
temperatureLabelBottomConstraint.constant = temperatureLabelBottomDistance
return
}
if distance <= 268.0 + bottomSafeArea
{
temperatureLabelBottomConstraint.constant = distance + temperatureLabelBottomDistance
}
else
{
temperatureLabelBottomConstraint.constant = 268.0 + temperatureLabelBottomDistance
}
}
}
``` | /content/code_sandbox/Pulley/PrimaryContentViewController.swift | swift | 2016-07-08T21:57:00 | 2024-08-10T19:44:06 | Pulley | 52inc/Pulley | 2,009 | 802 |
```objective-c
#import <UIKit/UIKit.h>
//! Project version number for Pulley.
FOUNDATION_EXPORT double PulleyVersionNumber;
//! Project version string for Pulley.
FOUNDATION_EXPORT const unsigned char PulleyVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <Pulley/PublicHeader.h>
``` | /content/code_sandbox/Pulley/Pulley.h | objective-c | 2016-07-08T21:57:00 | 2024-08-10T19:44:06 | Pulley | 52inc/Pulley | 2,009 | 69 |
```swift
//
// CustomMaskExample.swift
// Pulley
//
// Created by Connor Power on 19.08.18.
//
import UIKit
struct CustomMaskExample {
// MARK: - Constants
private struct Constants {
static let cornerRadius: CGFloat = 8.0
static let cutoutDistanceFromEdge: CGFloat = 32.0
static let cutoutRadius: CGFloat = 8.0
}
// MARK: - Functions
func customMask(for bounds: CGRect) -> UIBezierPath {
let maxX = bounds.maxX
let maxY = bounds.maxY
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: maxY))
// Left hand edge
path.addLine(to: CGPoint(x: 0, y: Constants.cornerRadius))
// Top left rounded corner
path.addArc(withCenter: CGPoint(x: Constants.cornerRadius, y: Constants.cornerRadius),
radius: Constants.cornerRadius,
startAngle: CGFloat.pi,
endAngle: 1.5 * CGFloat.pi,
clockwise: true)
// Top edge left cutout section
path.addLine(to: CGPoint(x: Constants.cutoutDistanceFromEdge - Constants.cutoutRadius, y: 0))
path.addArc(withCenter: CGPoint(x: Constants.cutoutDistanceFromEdge, y: 0),
radius: Constants.cutoutRadius,
startAngle: CGFloat.pi,
endAngle: 2.0 * CGFloat.pi,
clockwise: false)
path.addLine(to: CGPoint(x: Constants.cutoutDistanceFromEdge + Constants.cutoutRadius, y: 0))
// Top edge right cutout section
path.addLine(to: CGPoint(x: maxX - Constants.cutoutDistanceFromEdge - Constants.cutoutRadius, y: 0))
path.addArc(withCenter: CGPoint(x: maxX - Constants.cutoutDistanceFromEdge, y: 0),
radius: Constants.cutoutRadius,
startAngle: CGFloat.pi,
endAngle: 2.0 * CGFloat.pi,
clockwise: false)
path.addLine(to: CGPoint(x: maxX - Constants.cutoutDistanceFromEdge + Constants.cutoutRadius, y: 0))
path.addLine(to: CGPoint(x: maxX - Constants.cornerRadius, y: 0))
// Top right rounded corner
path.addArc(withCenter: CGPoint(x: maxX - Constants.cornerRadius, y: Constants.cornerRadius),
radius: Constants.cornerRadius,
startAngle: 1.5 * CGFloat.pi,
endAngle: 2.0 * CGFloat.pi,
clockwise: true)
// Right hand edge
path.addLine(to: CGPoint(x: maxX, y: maxY))
// Bottom edge
path.addLine(to: CGPoint(x: 0, y: maxY))
path.close()
path.fill()
return path
}
}
``` | /content/code_sandbox/Pulley/CustomMaskExample.swift | swift | 2016-07-08T21:57:00 | 2024-08-10T19:44:06 | Pulley | 52inc/Pulley | 2,009 | 607 |
```swift
//
// AppDelegate.swift
// Pulley
//
// Created by Brendan Lee on 7/6/16.
//
import UIKit
import Pulley
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool
{
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
// To create from a Storyboard
window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()!
// To create in code (uncomment this block)
/*
let mainContentVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PrimaryContentViewController")
let drawerContentVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DrawerContentViewController")
let pulleyDrawerVC = PulleyViewController(contentViewController: mainContentVC, drawerViewController: drawerContentVC)
// Uncomment this next line to give the drawer a starting position, in this case: closed.
// pulleyDrawerVC.initialDrawerPosition = .closed
window?.rootViewController = pulleyDrawerVC
*/
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
``` | /content/code_sandbox/Pulley/AppDelegate.swift | swift | 2016-07-08T21:57:00 | 2024-08-10T19:44:06 | Pulley | 52inc/Pulley | 2,009 | 590 |
```swift
//
// PulleyViewController.swift
// Pulley
//
// Created by Brendan Lee on 7/6/16.
//
import UIKit
/**
* The base delegate protocol for Pulley delegates.
*/
@objc public protocol PulleyDelegate: AnyObject {
/** This is called after size changes, so if you care about the bottomSafeArea property for custom UI layout, you can use this value.
* NOTE: It's not called *during* the transition between sizes (such as in an animation coordinator), but rather after the resize is complete.
*/
@objc optional func drawerPositionDidChange(drawer: PulleyViewController, bottomSafeArea: CGFloat)
/**
* Make UI adjustments for when Pulley goes to 'fullscreen'. Bottom safe area is provided for your convenience.
*/
@objc optional func makeUIAdjustmentsForFullscreen(progress: CGFloat, bottomSafeArea: CGFloat)
/**
* Make UI adjustments for changes in the drawer's distance-to-bottom. Bottom safe area is provided for your convenience.
*/
@objc optional func drawerChangedDistanceFromBottom(drawer: PulleyViewController, distance: CGFloat, bottomSafeArea: CGFloat)
/**
* Called when the current drawer display mode changes (leftSide vs bottomDrawer). Make UI changes to account for this here.
*/
@objc optional func drawerDisplayModeDidChange(drawer: PulleyViewController)
}
/**
* View controllers in the drawer can implement this to receive changes in state or provide values for the different drawer positions.
*/
@objc public protocol PulleyDrawerViewControllerDelegate: PulleyDelegate {
/**
* Provide the collapsed drawer height for Pulley. Pulley does NOT automatically handle safe areas for you, however: bottom safe area is provided for your convenience in computing a value to return.
*/
@objc optional func collapsedDrawerHeight(bottomSafeArea: CGFloat) -> CGFloat
/**
* Provide the partialReveal drawer height for Pulley. Pulley does NOT automatically handle safe areas for you, however: bottom safe area is provided for your convenience in computing a value to return.
*/
@objc optional func partialRevealDrawerHeight(bottomSafeArea: CGFloat) -> CGFloat
/**
* Return the support drawer positions for your drawer.
*/
@objc optional func supportedDrawerPositions() -> [PulleyPosition]
}
/**
* View controllers that are the main content can implement this to receive changes in state.
*/
@objc public protocol PulleyPrimaryContentControllerDelegate: PulleyDelegate {
// Not currently used for anything, but it's here for parity with the hopes that it'll one day be used.
}
/**
* A completion block used for animation callbacks.
*/
public typealias PulleyAnimationCompletionBlock = ((_ finished: Bool) -> Void)
/**
Represents a Pulley drawer position.
- collapsed: When the drawer is in its smallest form, at the bottom of the screen.
- partiallyRevealed: When the drawer is partially revealed.
- open: When the drawer is fully open.
- closed: When the drawer is off-screen at the bottom of the view. Note: Users cannot close or reopen the drawer on their own. You must set this programatically
*/
@objc public class PulleyPosition: NSObject {
public static let collapsed = PulleyPosition(rawValue: 0)
public static let partiallyRevealed = PulleyPosition(rawValue: 1)
public static let open = PulleyPosition(rawValue: 2)
public static let closed = PulleyPosition(rawValue: 3)
public static let all: [PulleyPosition] = [
.collapsed,
.partiallyRevealed,
.open,
.closed
]
public static let compact: [PulleyPosition] = [
.collapsed,
.open,
.closed
]
public let rawValue: Int
public init(rawValue: Int) {
if rawValue < 0 || rawValue > 3 {
print("PulleyViewController: A raw value of \(rawValue) is not supported. You have to use one of the predefined values in PulleyPosition. Defaulting to `collapsed`.")
self.rawValue = 0
} else {
self.rawValue = rawValue
}
}
/// Return one of the defined positions for the given string.
///
/// - Parameter string: The string, preferably obtained by `stringFor(position:)`
/// - Returns: The `PulleyPosition` or `.collapsed` if the string didn't match.
public static func positionFor(string: String?) -> PulleyPosition {
guard let positionString = string?.lowercased() else {
return .collapsed
}
switch positionString {
case "collapsed":
return .collapsed
case "partiallyrevealed":
return .partiallyRevealed
case "open":
return .open
case "closed":
return .closed
default:
print("PulleyViewController: Position for string '\(positionString)' not found. Available values are: collapsed, partiallyRevealed, open, and closed. Defaulting to collapsed.")
return .collapsed
}
}
public override func isEqual(_ object: Any?) -> Bool {
guard let position = object as? PulleyPosition else {
return false
}
return self.rawValue == position.rawValue
}
public override var description: String {
switch rawValue {
case 0:
return "collapsed"
case 1:
return "partiallyrevealed"
case 2:
return "open"
case 3:
return "closed"
default:
return "collapsed"
}
}
}
/// Represents the current display mode for Pulley
///
/// - panel: Show as a floating panel (replaces: leftSide)
/// - drawer: Show as a bottom drawer (replaces: bottomDrawer)
/// - compact: Show as a compacted bottom drawer (support for iPhone SE size class)
/// - automatic: Determine it based on device / orientation / size class (like Maps.app)
public enum PulleyDisplayMode {
case panel
case drawer
case compact
case automatic
}
/// Represents the positioning of the drawer when the `displayMode` is set to either `PulleyDisplayMode.panel` or `PulleyDisplayMode.automatic`.
///
/// - topLeft: The drawer will placed in the upper left corner
/// - topRight: The drawer will placed in the upper right corner
/// - bottomLeft: The drawer will placed in the bottom left corner
/// - bottomRight: The drawer will placed in the bottom right corner
public enum PulleyPanelCornerPlacement {
case topLeft
case topRight
case bottomLeft
case bottomRight
}
/// Represents the positioning of the drawer when the `displayMode` is set to either `PulleyDisplayMode.panel` or `PulleyDisplayMode.automatic`.
/// - bottomLeft: The drawer will placed in the bottom left corner
/// - bottomRight: The drawer will placed in the bottom right corner
public enum PulleyCompactCornerPlacement {
case bottomLeft
case bottomRight
}
/// Represents the 'snap' mode for Pulley. The default is 'nearest position'. You can use 'nearestPositionUnlessExceeded' to make the drawer feel lighter or heavier.
///
/// - nearestPosition: Snap to the nearest position when scroll stops
/// - nearestPositionUnlessExceeded: Snap to the nearest position when scroll stops, unless the distance is greater than 'threshold', in which case advance to the next drawer position.
public enum PulleySnapMode {
case nearestPosition
case nearestPositionUnlessExceeded(threshold: CGFloat)
}
private let kPulleyDefaultCollapsedHeight: CGFloat = 68.0
private let kPulleyDefaultPartialRevealHeight: CGFloat = 264.0
open class PulleyViewController: UIViewController, PulleyDrawerViewControllerDelegate {
// Interface Builder
/// When using with Interface Builder only! Connect a containing view to this outlet.
@IBOutlet public var primaryContentContainerView: UIView!
/// When using with Interface Builder only! Connect a containing view to this outlet.
@IBOutlet public var drawerContentContainerView: UIView!
// Internal
fileprivate let primaryContentContainer: UIView = UIView()
fileprivate let drawerContentContainer: UIView = UIView()
fileprivate let drawerShadowView: UIView = UIView()
fileprivate let drawerScrollView: PulleyPassthroughScrollView = PulleyPassthroughScrollView()
fileprivate let backgroundDimmingView: UIView = UIView()
fileprivate var dimmingViewTapRecognizer: UITapGestureRecognizer?
fileprivate var lastDragTargetContentOffset: CGPoint = CGPoint.zero
// Public
public let bounceOverflowMargin: CGFloat = 20.0
/// The current content view controller (shown behind the drawer).
public fileprivate(set) var primaryContentViewController: UIViewController! {
willSet {
guard let controller = primaryContentViewController else {
return
}
controller.willMove(toParent: nil)
controller.view.removeFromSuperview()
controller.removeFromParent()
}
didSet {
guard let controller = primaryContentViewController else {
return
}
addChild(controller)
primaryContentContainer.addSubview(controller.view)
controller.view.constrainToParent()
controller.didMove(toParent: self)
if self.isViewLoaded
{
self.view.setNeedsLayout()
self.setNeedsSupportedDrawerPositionsUpdate()
}
}
}
/// The current drawer view controller (shown in the drawer).
public fileprivate(set) var drawerContentViewController: UIViewController! {
willSet {
guard let controller = drawerContentViewController else {
return
}
controller.willMove(toParent: nil)
controller.view.removeFromSuperview()
controller.removeFromParent()
}
didSet {
guard let controller = drawerContentViewController else {
return
}
addChild(controller)
drawerContentContainer.addSubview(controller.view)
controller.view.constrainToParent()
controller.didMove(toParent: self)
if self.isViewLoaded
{
self.view.setNeedsLayout()
self.setNeedsSupportedDrawerPositionsUpdate()
}
}
}
/// Get the current bottom safe area for Pulley. This is a convenience accessor. Most delegate methods where you'd need it will deliver it as a parameter.
public var bottomSafeSpace: CGFloat {
get {
return pulleySafeAreaInsets.bottom
}
}
/// The content view controller and drawer controller can receive delegate events already. This lets another object observe the changes, if needed.
public weak var delegate: PulleyDelegate?
/// The current position of the drawer.
public fileprivate(set) var drawerPosition: PulleyPosition = .collapsed {
didSet {
setNeedsStatusBarAppearanceUpdate()
}
}
// The visible height of the drawer. Useful for adjusting the display of content in the main content view.
public var visibleDrawerHeight: CGFloat {
if drawerPosition == .closed {
return 0.0
} else {
return drawerScrollView.bounds.height
}
}
// Returns default blur style depends on iOS version.
private static var defaultBlurEffect: UIBlurEffect.Style {
if #available(iOS 13, *) {
return .systemUltraThinMaterial
} else {
return .extraLight
}
}
/// The background visual effect layer for the drawer. By default this is the extraLight effect. You can change this if you want, or assign nil to remove it.
public var drawerBackgroundVisualEffectView: UIVisualEffectView? = UIVisualEffectView(effect: UIBlurEffect(style: defaultBlurEffect)) {
willSet {
drawerBackgroundVisualEffectView?.removeFromSuperview()
}
didSet {
if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView, self.isViewLoaded
{
drawerScrollView.insertSubview(drawerBackgroundVisualEffectView, aboveSubview: drawerShadowView)
drawerBackgroundVisualEffectView.clipsToBounds = true
drawerBackgroundVisualEffectView.layer.cornerRadius = drawerCornerRadius
self.view.setNeedsLayout()
}
}
}
/// The inset from the top safe area when the drawer is fully open. This property is only for the 'drawer' displayMode. Use panelInsets to control the top/bottom/left/right insets for the panel.
@IBInspectable public var drawerTopInset: CGFloat = 20.0 {
didSet {
if oldValue != drawerTopInset, self.isViewLoaded
{
self.view.setNeedsLayout()
}
}
}
/// This replaces the previous panelInsetLeft and panelInsetTop properties. Depending on what corner placement is being used, different values from this struct will apply. For example, 'topLeft' corner placement will utilize the .top, .left, and .bottom inset properties and it will ignore the .right property (use panelWidth property to specify width)
@IBInspectable public var panelInsets: UIEdgeInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0) {
didSet {
if oldValue != panelInsets, self.isViewLoaded
{
self.view.setNeedsLayout()
}
}
}
/// The width of the panel in panel displayMode
@IBInspectable public var panelWidth: CGFloat = 325.0 {
didSet {
if oldValue != panelWidth, self.isViewLoaded
{
self.view.setNeedsLayout()
}
}
}
/// Depending on what corner placement is being used, different values from this struct will apply. For example, 'bottomRight' corner placement will utilize the .top, .right, and .bottom inset properties and it will ignore the .left property (use compactWidth property to specify width)
@IBInspectable public var compactInsets: UIEdgeInsets = UIEdgeInsets(top: 8.0, left: 8.0, bottom: 10.0, right: 8.0) {
didSet {
if oldValue != compactInsets, self.isViewLoaded
{
self.view.setNeedsLayout()
}
}
}
/// The width of the drawer in compact displayMode
@IBInspectable public var compactWidth: CGFloat = 292.0 {
didSet {
if oldValue != compactWidth, self.isViewLoaded
{
self.view.setNeedsLayout()
}
}
}
/// The corner radius for the drawer.
/// Note: This property is ignored if your drawerContentViewController's view.layer.mask has a custom mask applied using a CAShapeLayer.
/// Note: Custom CAShapeLayer as your drawerContentViewController's view.layer mask will override Pulley's internal corner rounding and use that mask as the drawer mask.
@IBInspectable public var drawerCornerRadius: CGFloat = 13.0 {
didSet {
if self.isViewLoaded
{
if oldValue != drawerCornerRadius {
self.view.setNeedsLayout()
}
drawerBackgroundVisualEffectView?.layer.cornerRadius = drawerCornerRadius
}
}
}
/// The opacity of the drawer shadow.
@IBInspectable public var shadowOpacity: Float = 0.1 {
didSet {
if self.isViewLoaded
{
drawerShadowView.layer.shadowOpacity = shadowOpacity
if oldValue != shadowOpacity
{
self.view.setNeedsLayout()
}
}
}
}
/// The radius of the drawer shadow.
@IBInspectable public var shadowRadius: CGFloat = 3.0 {
didSet {
if self.isViewLoaded
{
drawerShadowView.layer.shadowRadius = shadowRadius
if oldValue != shadowRadius
{
self.view.setNeedsLayout()
}
}
}
}
/// The offset of the drawer shadow.
@IBInspectable public var shadowOffset = CGSize(width: 0.0, height: -3.0) {
didSet {
if self.isViewLoaded
{
drawerShadowView.layer.shadowOffset = shadowOffset
if oldValue != shadowOffset
{
self.view.setNeedsLayout()
}
}
}
}
/// The opaque color of the background dimming view.
@IBInspectable public var backgroundDimmingColor: UIColor = UIColor.black {
didSet {
if self.isViewLoaded
{
backgroundDimmingView.backgroundColor = backgroundDimmingColor
}
}
}
/// The maximum amount of opacity when dimming.
@IBInspectable public var backgroundDimmingOpacity: CGFloat = 0.5 {
didSet {
if self.isViewLoaded
{
self.scrollViewDidScroll(drawerScrollView)
}
}
}
/// The drawer scrollview's delaysContentTouches setting
@IBInspectable public var delaysContentTouches: Bool = true {
didSet {
if self.isViewLoaded
{
drawerScrollView.delaysContentTouches = delaysContentTouches
}
}
}
/// The drawer scrollview's canCancelContentTouches setting
@IBInspectable public var canCancelContentTouches: Bool = true {
didSet {
if self.isViewLoaded
{
drawerScrollView.canCancelContentTouches = canCancelContentTouches
}
}
}
/// The starting position for the drawer when it first loads
public var initialDrawerPosition: PulleyPosition = .collapsed
/// The display mode for Pulley. Default is 'drawer', which preserves the previous behavior of Pulley. If you want it to adapt automatically, choose 'automatic'. The current display mode is available by using the 'currentDisplayMode' property.
public var displayMode: PulleyDisplayMode = .drawer {
didSet {
if self.isViewLoaded
{
self.view.setNeedsLayout()
}
}
}
/// The Y positioning for Pulley. This property is only oberserved when `displayMode` is set to `.automatic` or `.pannel`. Default value is `.topLeft`.
public var panelCornerPlacement: PulleyPanelCornerPlacement = .topLeft {
didSet {
if self.isViewLoaded
{
self.view.setNeedsLayout()
}
}
}
/// The Y positioning for Pulley. This property is only oberserved when `displayMode` is set to `.automatic` or `.compact`. Default value is `.bottomLeft`.
public var compactCornerPlacement: PulleyCompactCornerPlacement = .bottomLeft {
didSet {
if self.isViewLoaded
{
self.view.setNeedsLayout()
}
}
}
/// This is here exclusively to support IBInspectable in Interface Builder because Interface Builder can't deal with enums. If you're doing this in code use the -initialDrawerPosition property instead. Available strings are: open, closed, partiallyRevealed, collapsed
@IBInspectable public var initialDrawerPositionFromIB: String? {
didSet {
initialDrawerPosition = PulleyPosition.positionFor(string: initialDrawerPositionFromIB)
}
}
/// Whether the drawer's position can be changed by the user. If set to `false`, the only way to move the drawer is programmatically. Defaults to `true`.
@IBInspectable public var allowsUserDrawerPositionChange: Bool = true {
didSet {
enforceCanScrollDrawer()
}
}
/// The animation duration for setting the drawer position
@IBInspectable public var animationDuration: TimeInterval = 0.3
/// The animation delay for setting the drawer position
@IBInspectable public var animationDelay: TimeInterval = 0.0
/// The spring damping for setting the drawer position
@IBInspectable public var animationSpringDamping: CGFloat = 0.75
/// The spring's initial velocity for setting the drawer position
@IBInspectable public var animationSpringInitialVelocity: CGFloat = 0.0
/// This setting allows you to enable/disable Pulley automatically insetting the drawer on the left/right when in 'bottomDrawer' display mode in a horizontal orientation on a device with a 'notch' or other left/right obscurement.
@IBInspectable public var adjustDrawerHorizontalInsetToSafeArea: Bool = true {
didSet {
if self.isViewLoaded
{
self.view.setNeedsLayout()
}
}
}
/// The animation options for setting the drawer position
public var animationOptions: UIView.AnimationOptions = [.curveEaseInOut]
/// The drawer snap mode
public var snapMode: PulleySnapMode = .nearestPositionUnlessExceeded(threshold: 20.0)
// The feedback generator to use for drawer positon changes. Note: This is 'Any' to preserve iOS 9 compatibilty. Assign a UIFeedbackGenerator to this property. Anything else will be ignored.
public var feedbackGenerator: Any?
/// Access to the safe areas that Pulley is using for layout (provides compatibility for iOS < 11)
open var pulleySafeAreaInsets: UIEdgeInsets {
var safeAreaBottomInset: CGFloat = 0
var safeAreaLeftInset: CGFloat = 0
var safeAreaRightInset: CGFloat = 0
var safeAreaTopInset: CGFloat = 0
if #available(iOS 11.0, *)
{
safeAreaBottomInset = view.safeAreaInsets.bottom
safeAreaLeftInset = view.safeAreaInsets.left
safeAreaRightInset = view.safeAreaInsets.right
safeAreaTopInset = view.safeAreaInsets.top
}
else
{
safeAreaBottomInset = self.bottomLayoutGuide.length
safeAreaTopInset = self.topLayoutGuide.length
}
return UIEdgeInsets(top: safeAreaTopInset, left: safeAreaLeftInset, bottom: safeAreaBottomInset, right: safeAreaRightInset)
}
/// Get the current drawer distance. This value is equivalent in nature to the one delivered by PulleyDelegate's `drawerChangedDistanceFromBottom` callback.
public var drawerDistanceFromBottom: (distance: CGFloat, bottomSafeArea: CGFloat) {
if self.isViewLoaded
{
let lowestStop = getStopList().min() ?? 0.0
return (distance: drawerScrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom)
}
return (distance: 0.0, bottomSafeArea: 0.0)
}
// The position the pulley should animate to when the background is tapped. Default is collapsed.
public var positionWhenDimmingBackgroundIsTapped:PulleyPosition = .collapsed
/// Get all gesture recognizers in the drawer scrollview
public var drawerGestureRecognizers: [UIGestureRecognizer] {
get {
return drawerScrollView.gestureRecognizers ?? [UIGestureRecognizer]()
}
}
/// Get the drawer scrollview's pan gesture recognizer
public var drawerPanGestureRecognizer: UIPanGestureRecognizer {
get {
return drawerScrollView.panGestureRecognizer
}
}
/// The drawer positions supported by the drawer
fileprivate var supportedPositions: [PulleyPosition] = PulleyPosition.all {
didSet {
guard self.isViewLoaded else {
return
}
guard supportedPositions.count > 0 else {
supportedPositions = self.currentDisplayMode == .compact ? PulleyPosition.compact : PulleyPosition.all
return
}
if oldValue != supportedPositions {
self.view.setNeedsLayout()
}
if supportedPositions.contains(drawerPosition)
{
setDrawerPosition(position: drawerPosition, animated: false)
}
else if (self.currentDisplayMode == .compact && drawerPosition == .partiallyRevealed && supportedPositions.contains(.open))
{
setDrawerPosition(position: .open, animated: false)
}
else
{
let lowestDrawerState: PulleyPosition = supportedPositions.filter({ $0 != .closed }).min { (pos1, pos2) -> Bool in
return pos1.rawValue < pos2.rawValue
} ?? .collapsed
setDrawerPosition(position: lowestDrawerState, animated: false)
}
enforceCanScrollDrawer()
}
}
/// The currently rendered display mode for Pulley. This will match displayMode unless you have it set to 'automatic'. This will provide the 'actual' display mode (never automatic).
public fileprivate(set) var currentDisplayMode: PulleyDisplayMode = .automatic {
didSet {
if oldValue != currentDisplayMode
{
if self.isViewLoaded
{
self.view.setNeedsLayout()
self.setNeedsSupportedDrawerPositionsUpdate()
}
delegate?.drawerDisplayModeDidChange?(drawer: self)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerDisplayModeDidChange?(drawer: self)
(primaryContentContainer as? PulleyPrimaryContentControllerDelegate)?.drawerDisplayModeDidChange?(drawer: self)
}
}
}
fileprivate var isAnimatingDrawerPosition: Bool = false
fileprivate var isChangingDrawerPosition: Bool = false
/// The height of the open position for the drawer
public var heightOfOpenDrawer: CGFloat {
let safeAreaTopInset = pulleySafeAreaInsets.top
let safeAreaBottomInset = pulleySafeAreaInsets.bottom
var height = self.view.bounds.height - safeAreaTopInset
if currentDisplayMode == .panel {
height -= (panelInsets.top + bounceOverflowMargin)
height -= (panelInsets.bottom + safeAreaBottomInset)
} else if currentDisplayMode == .drawer {
height -= drawerTopInset
}
return height
}
/**
Initialize the drawer controller programmtically.
- parameter contentViewController: The content view controller. This view controller is shown behind the drawer.
- parameter drawerViewController: The view controller to display inside the drawer.
- note: The drawer VC is 20pts too tall in order to have some extra space for the bounce animation. Make sure your constraints / content layout take this into account.
- returns: A newly created Pulley drawer.
*/
required public init(contentViewController: UIViewController, drawerViewController: UIViewController) {
super.init(nibName: nil, bundle: nil)
({
self.primaryContentViewController = contentViewController
self.drawerContentViewController = drawerViewController
})()
}
/**
Initialize the drawer controller from Interface Builder.
- note: Usage notes: Make 2 container views in Interface Builder and connect their outlets to -primaryContentContainerView and -drawerContentContainerView. Then use embed segues to place your content/drawer view controllers into the appropriate container.
- parameter aDecoder: The NSCoder to decode from.
- returns: A newly created Pulley drawer.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func loadView() {
super.loadView()
// IB Support
if primaryContentContainerView != nil
{
primaryContentContainerView.removeFromSuperview()
}
if drawerContentContainerView != nil
{
drawerContentContainerView.removeFromSuperview()
}
// Setup
primaryContentContainer.backgroundColor = UIColor.white
definesPresentationContext = true
drawerScrollView.bounces = false
drawerScrollView.delegate = self
drawerScrollView.clipsToBounds = false
drawerScrollView.showsVerticalScrollIndicator = false
drawerScrollView.showsHorizontalScrollIndicator = false
drawerScrollView.delaysContentTouches = delaysContentTouches
drawerScrollView.canCancelContentTouches = canCancelContentTouches
drawerScrollView.backgroundColor = UIColor.clear
drawerScrollView.decelerationRate = UIScrollView.DecelerationRate.fast
drawerScrollView.scrollsToTop = false
drawerScrollView.touchDelegate = self
drawerShadowView.layer.shadowOpacity = shadowOpacity
drawerShadowView.layer.shadowRadius = shadowRadius
drawerShadowView.layer.shadowOffset = shadowOffset
drawerShadowView.backgroundColor = UIColor.clear
drawerContentContainer.backgroundColor = UIColor.clear
backgroundDimmingView.backgroundColor = backgroundDimmingColor
backgroundDimmingView.isUserInteractionEnabled = false
backgroundDimmingView.alpha = 0.0
drawerBackgroundVisualEffectView?.clipsToBounds = true
dimmingViewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(PulleyViewController.dimmingViewTapRecognizerAction(gestureRecognizer:)))
backgroundDimmingView.addGestureRecognizer(dimmingViewTapRecognizer!)
drawerScrollView.addSubview(drawerShadowView)
if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView
{
drawerScrollView.addSubview(drawerBackgroundVisualEffectView)
drawerBackgroundVisualEffectView.layer.cornerRadius = drawerCornerRadius
}
drawerScrollView.addSubview(drawerContentContainer)
primaryContentContainer.backgroundColor = UIColor.white
self.view.backgroundColor = UIColor.white
self.view.addSubview(primaryContentContainer)
self.view.addSubview(backgroundDimmingView)
self.view.addSubview(drawerScrollView)
primaryContentContainer.constrainToParent()
}
override open func viewDidLoad() {
super.viewDidLoad()
// IB Support
if primaryContentViewController == nil || drawerContentViewController == nil
{
assert(primaryContentContainerView != nil && drawerContentContainerView != nil, "When instantiating from Interface Builder you must provide container views with an embedded view controller.")
// Locate main content VC
for child in self.children
{
if child.view == primaryContentContainerView.subviews.first
{
primaryContentViewController = child
}
if child.view == drawerContentContainerView.subviews.first
{
drawerContentViewController = child
}
}
assert(primaryContentViewController != nil && drawerContentViewController != nil, "Container views must contain an embedded view controller.")
}
enforceCanScrollDrawer()
setDrawerPosition(position: initialDrawerPosition, animated: false)
scrollViewDidScroll(drawerScrollView)
delegate?.drawerDisplayModeDidChange?(drawer: self)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerDisplayModeDidChange?(drawer: self)
(primaryContentContainer as? PulleyPrimaryContentControllerDelegate)?.drawerDisplayModeDidChange?(drawer: self)
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setNeedsSupportedDrawerPositionsUpdate()
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Make sure our view controller views are subviews of the right view (Resolves #21 issue with changing the presentation context)
// May be nil during initial layout
if let primary = primaryContentViewController
{
if primary.view.superview != nil && primary.view.superview != primaryContentContainer
{
primaryContentContainer.addSubview(primary.view)
primaryContentContainer.sendSubviewToBack(primary.view)
primary.view.constrainToParent()
}
}
// May be nil during initial layout
if let drawer = drawerContentViewController
{
if drawer.view.superview != nil && drawer.view.superview != drawerContentContainer
{
drawerContentContainer.addSubview(drawer.view)
drawerContentContainer.sendSubviewToBack(drawer.view)
drawer.view.constrainToParent()
}
}
let safeAreaTopInset = pulleySafeAreaInsets.top
let safeAreaBottomInset = pulleySafeAreaInsets.bottom
let safeAreaLeftInset = pulleySafeAreaInsets.left
let safeAreaRightInset = pulleySafeAreaInsets.right
var automaticDisplayMode: PulleyDisplayMode = .drawer
if (self.view.bounds.width >= 600.0 ) {
switch self.traitCollection.horizontalSizeClass {
case .compact:
automaticDisplayMode = .compact
default:
automaticDisplayMode = .panel
}
}
let displayModeForCurrentLayout: PulleyDisplayMode = displayMode != .automatic ? displayMode : automaticDisplayMode
currentDisplayMode = displayModeForCurrentLayout
if displayModeForCurrentLayout == .drawer
{
// Bottom inset for safe area / bottomLayoutGuide
if #available(iOS 11, *) {
self.drawerScrollView.contentInsetAdjustmentBehavior = .scrollableAxes
} else {
self.automaticallyAdjustsScrollViewInsets = false
self.drawerScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: self.bottomLayoutGuide.length, right: 0)
self.drawerScrollView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: self.bottomLayoutGuide.length, right: 0) // (usefull if visible..)
}
let lowestStop = getStopList().min() ?? 0
let adjustedLeftSafeArea = adjustDrawerHorizontalInsetToSafeArea ? safeAreaLeftInset : 0.0
let adjustedRightSafeArea = adjustDrawerHorizontalInsetToSafeArea ? safeAreaRightInset : 0.0
if supportedPositions.contains(.open)
{
// Layout scrollview
drawerScrollView.frame = CGRect(x: adjustedLeftSafeArea, y: drawerTopInset + safeAreaTopInset, width: self.view.bounds.width - adjustedLeftSafeArea - adjustedRightSafeArea, height: heightOfOpenDrawer)
}
else
{
// Layout scrollview
let adjustedTopInset: CGFloat = getStopList().max() ?? 0.0
drawerScrollView.frame = CGRect(x: adjustedLeftSafeArea, y: self.view.bounds.height - adjustedTopInset, width: self.view.bounds.width - adjustedLeftSafeArea - adjustedRightSafeArea, height: adjustedTopInset)
}
drawerScrollView.addSubview(drawerShadowView)
if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView
{
drawerScrollView.addSubview(drawerBackgroundVisualEffectView)
drawerBackgroundVisualEffectView.layer.cornerRadius = drawerCornerRadius
}
drawerScrollView.addSubview(drawerContentContainer)
drawerContentContainer.frame = CGRect(x: 0, y: drawerScrollView.bounds.height - lowestStop, width: drawerScrollView.bounds.width, height: drawerScrollView.bounds.height + bounceOverflowMargin)
drawerBackgroundVisualEffectView?.frame = drawerContentContainer.frame
drawerShadowView.frame = drawerContentContainer.frame
drawerScrollView.contentSize = CGSize(width: drawerScrollView.bounds.width, height: (drawerScrollView.bounds.height - lowestStop) + drawerScrollView.bounds.height - safeAreaBottomInset + (bounceOverflowMargin - 5.0))
// Update rounding mask and shadows
let borderPath = drawerMaskingPath(byRoundingCorners: [.topLeft, .topRight, .bottomLeft, .bottomRight]).cgPath
let cardMaskLayer = CAShapeLayer()
cardMaskLayer.path = borderPath
cardMaskLayer.frame = drawerContentContainer.bounds
cardMaskLayer.fillColor = UIColor.white.cgColor
cardMaskLayer.backgroundColor = UIColor.clear.cgColor
drawerContentContainer.layer.mask = cardMaskLayer
drawerShadowView.layer.shadowPath = borderPath
backgroundDimmingView.frame = CGRect(x: 0.0, y: 0.0, width: self.view.bounds.width, height: self.view.bounds.height + drawerScrollView.contentSize.height)
drawerScrollView.transform = CGAffineTransform.identity
backgroundDimmingView.isHidden = false
}
else
{
// Bottom inset for safe area / bottomLayoutGuide
if #available(iOS 11, *) {
self.drawerScrollView.contentInsetAdjustmentBehavior = .scrollableAxes
} else {
self.automaticallyAdjustsScrollViewInsets = false
self.drawerScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0.0, right: 0)
self.drawerScrollView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0.0, right: 0)
}
// Layout container
var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight
var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight?(bottomSafeArea: safeAreaBottomInset) ?? kPulleyDefaultCollapsedHeight
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight?(bottomSafeArea: safeAreaBottomInset) ?? kPulleyDefaultPartialRevealHeight
}
var lowestStop: CGFloat = 0
var xOrigin: CGFloat = 0
var yOrigin: CGFloat = 0
let width = displayModeForCurrentLayout == .compact ? compactWidth : panelWidth
if (displayModeForCurrentLayout == .compact)
{
lowestStop = [(self.view.bounds.size.height - compactInsets.bottom - safeAreaTopInset), collapsedHeight, partialRevealHeight].min() ?? 0
xOrigin = (compactCornerPlacement == .bottomLeft) ? (safeAreaLeftInset + compactInsets.left) : (self.view.bounds.maxX - (safeAreaRightInset + compactInsets.right) - compactWidth)
yOrigin = (compactInsets.top + safeAreaTopInset)
}
else
{
lowestStop = [(self.view.bounds.size.height - panelInsets.bottom - safeAreaTopInset), collapsedHeight, partialRevealHeight].min() ?? 0
xOrigin = (panelCornerPlacement == .bottomLeft || panelCornerPlacement == .topLeft) ? (safeAreaLeftInset + panelInsets.left) : (self.view.bounds.maxX - (safeAreaRightInset + panelInsets.right) - panelWidth)
yOrigin = (panelCornerPlacement == .bottomLeft || panelCornerPlacement == .bottomRight) ? (panelInsets.top + safeAreaTopInset) : (panelInsets.top + safeAreaTopInset + bounceOverflowMargin)
}
if supportedPositions.contains(.open)
{
// Layout scrollview
drawerScrollView.frame = CGRect(x: xOrigin, y: yOrigin, width: width, height: heightOfOpenDrawer)
}
else
{
// Layout scrollview
let adjustedTopInset: CGFloat = supportedPositions.contains(.partiallyRevealed) ? partialRevealHeight : collapsedHeight
drawerScrollView.frame = CGRect(x: xOrigin, y: yOrigin, width: width, height: adjustedTopInset)
}
your_sha256_hash()
drawerScrollView.contentSize = CGSize(width: drawerScrollView.bounds.width, height: self.view.bounds.height + (self.view.bounds.height - lowestStop))
if (displayModeForCurrentLayout == .compact)
{
switch compactCornerPlacement {
case .bottomLeft, .bottomRight:
drawerScrollView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}
}
else
{
switch panelCornerPlacement {
case .topLeft, .topRight:
drawerScrollView.transform = CGAffineTransform(scaleX: 1.0, y: -1.0)
case .bottomLeft, .bottomRight:
drawerScrollView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}
}
backgroundDimmingView.isHidden = true
}
drawerContentContainer.transform = drawerScrollView.transform
drawerShadowView.transform = drawerScrollView.transform
drawerBackgroundVisualEffectView?.transform = drawerScrollView.transform
let lowestStop = getStopList().min() ?? 0
delegate?.drawerChangedDistanceFromBottom?(drawer: self, distance: drawerScrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: drawerScrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom)
(primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: drawerScrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom)
maskDrawerVisualEffectView()
maskBackgroundDimmingView()
// Do not need to set the the drawer position in layoutSubview if the position of the drawer is changing
// and the view is being layed out. If the drawer position is changing and the view is layed out (i.e.
// a value or constraints are bing updated) the drawer is always set to the last position,
// and no longer scrolls properly.
if self.isChangingDrawerPosition == false {
setDrawerPosition(position: drawerPosition, animated: false)
}
}
// MARK: Private State Updates
private func enforceCanScrollDrawer() {
guard isViewLoaded else {
return
}
drawerScrollView.isScrollEnabled = allowsUserDrawerPositionChange && supportedPositions.count > 1
}
func getStopList() -> [CGFloat] {
var drawerStops = [CGFloat]()
var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight
var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultCollapsedHeight
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultPartialRevealHeight
}
if supportedPositions.contains(.collapsed)
{
drawerStops.append(collapsedHeight)
}
if supportedPositions.contains(.partiallyRevealed)
{
drawerStops.append(partialRevealHeight)
}
if supportedPositions.contains(.open)
{
drawerStops.append((self.view.bounds.size.height - drawerTopInset - pulleySafeAreaInsets.top))
}
return drawerStops
}
/**
Returns a masking path appropriate for the drawer content. Either
an existing user-supplied mask from the `drawerContentViewController's`
view will be returned, or the default Pulley mask with the requested
rounded corners will be used.
- parameter corners: The corners to round if there is no custom mask
already applied to the `drawerContentViewController` view. If the
`drawerContentViewController` has a custom mask (supplied by the
user of this library), then the corners parameter will be ignored.
*/
private func drawerMaskingPath(byRoundingCorners corners: UIRectCorner) -> UIBezierPath {
// In lue of drawerContentViewController.view.layoutIfNeeded() whenever this function is called, if the viewController is loaded setNeedsLayout
if drawerContentViewController.isViewLoaded {
drawerContentViewController.view.setNeedsLayout()
}
let path: UIBezierPath
if let customPath = (drawerContentViewController.view.layer.mask as? CAShapeLayer)?.path {
path = UIBezierPath(cgPath: customPath)
} else {
path = UIBezierPath(roundedRect: drawerContentContainer.bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: drawerCornerRadius, height: drawerCornerRadius))
}
return path
}
private func maskDrawerVisualEffectView() {
if let drawerBackgroundVisualEffectView = drawerBackgroundVisualEffectView {
let path = drawerMaskingPath(byRoundingCorners: [.topLeft, .topRight])
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
drawerBackgroundVisualEffectView.layer.mask = maskLayer
}
}
/**
Mask backgroundDimmingView layer to avoid drawer background beeing darkened.
*/
private func maskBackgroundDimmingView() {
let cutoutHeight = 2 * drawerCornerRadius
let maskHeight = backgroundDimmingView.bounds.size.height - cutoutHeight - drawerScrollView.contentSize.height
let borderPath = drawerMaskingPath(byRoundingCorners: [.topLeft, .topRight])
// This applys the boarder path transform to the minimum x of the content container for iPhone X size devices
if let frame = drawerContentContainer.superview?.convert(drawerContentContainer.frame, to: self.view) {
borderPath.apply(CGAffineTransform(translationX: frame.minX, y: maskHeight))
} else {
borderPath.apply(CGAffineTransform(translationX: 0.0, y: maskHeight))
}
let maskLayer = CAShapeLayer()
// Invert mask to cut away the bottom part of the dimming view
borderPath.append(UIBezierPath(rect: backgroundDimmingView.bounds))
maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
maskLayer.path = borderPath.cgPath
backgroundDimmingView.layer.mask = maskLayer
}
open func prepareFeedbackGenerator() {
if #available(iOS 10.0, *) {
if let generator = feedbackGenerator as? UIFeedbackGenerator
{
generator.prepare()
}
}
}
open func triggerFeedbackGenerator() {
if #available(iOS 10.0, *) {
// prepareFeedbackGenerator() is also added to scrollViewWillEndDragging to improve time between haptic engine triggering feedback and the call to prepare.
prepareFeedbackGenerator()
(feedbackGenerator as? UIImpactFeedbackGenerator)?.impactOccurred()
(feedbackGenerator as? UISelectionFeedbackGenerator)?.selectionChanged()
(feedbackGenerator as? UINotificationFeedbackGenerator)?.notificationOccurred(.success)
}
}
/// Add a gesture recognizer to the drawer scrollview
///
/// - Parameter gestureRecognizer: The gesture recognizer to add
public func addDrawerGestureRecognizer(gestureRecognizer: UIGestureRecognizer) {
drawerScrollView.addGestureRecognizer(gestureRecognizer)
}
/// Remove a gesture recognizer from the drawer scrollview
///
/// - Parameter gestureRecognizer: The gesture recognizer to remove
public func removeDrawerGestureRecognizer(gestureRecognizer: UIGestureRecognizer) {
drawerScrollView.removeGestureRecognizer(gestureRecognizer)
}
/// Bounce the drawer to get user attention. Note: Only works in .drawer display mode and when the drawer is in .collapsed or .partiallyRevealed position.
///
/// - Parameters:
/// - bounceHeight: The height to bounce
/// - speedMultiplier: The multiplier to apply to the default speed of the animation. Note, default speed is 0.75.
public func bounceDrawer(bounceHeight: CGFloat = 50.0, speedMultiplier: Double = 0.75) {
guard drawerPosition == .collapsed || drawerPosition == .partiallyRevealed else {
print("Pulley: Error: You can only bounce the drawer when it's in the collapsed or partially revealed position.")
return
}
guard currentDisplayMode == .drawer else {
print("Pulley: Error: You can only bounce the drawer when it's in the .drawer display mode.")
return
}
let drawerStartingBounds = drawerScrollView.bounds
// Adapted from path_to_url
let factors: [CGFloat] = [0, 32, 60, 83, 100, 114, 124, 128, 128, 124, 114, 100, 83, 60, 32,
0, 24, 42, 54, 62, 64, 62, 54, 42, 24, 0, 18, 28, 32, 28, 18, 0]
var values = [CGFloat]()
for factor in factors
{
let positionOffset = (factor / 128.0) * bounceHeight
values.append(drawerStartingBounds.origin.y + positionOffset)
}
let animation = CAKeyframeAnimation(keyPath: "bounds.origin.y")
animation.repeatCount = 1
animation.duration = (32.0/30.0) * speedMultiplier
animation.fillMode = CAMediaTimingFillMode.forwards
animation.values = values
animation.isRemovedOnCompletion = true
animation.autoreverses = false
drawerScrollView.layer.add(animation, forKey: "bounceAnimation")
}
/**
Get a frame for moving backgroundDimmingView according to drawer position.
- parameter drawerPosition: drawer position in points
- returns: a frame for moving backgroundDimmingView according to drawer position
*/
private func backgroundDimmingViewFrameForDrawerPosition(_ drawerPosition: CGFloat) -> CGRect {
let cutoutHeight = (2 * drawerCornerRadius)
var backgroundDimmingViewFrame = backgroundDimmingView.frame
backgroundDimmingViewFrame.origin.y = 0 - drawerPosition + cutoutHeight
return backgroundDimmingViewFrame
}
private func your_sha256_hash() {
guard currentDisplayMode == .panel || currentDisplayMode == .compact else {
return
}
let lowestStop = getStopList().min() ?? 0
drawerContentContainer.frame = CGRect(x: 0.0, y: drawerScrollView.bounds.height - lowestStop , width: drawerScrollView.bounds.width, height: drawerScrollView.contentOffset.y + lowestStop)
drawerBackgroundVisualEffectView?.frame = drawerContentContainer.frame
drawerShadowView.frame = drawerContentContainer.frame
// Update rounding mask and shadows
let borderPath = drawerMaskingPath(byRoundingCorners: [.topLeft, .topRight, .bottomLeft, .bottomRight]).cgPath
let cardMaskLayer = CAShapeLayer()
cardMaskLayer.path = borderPath
cardMaskLayer.frame = drawerContentContainer.bounds
cardMaskLayer.fillColor = UIColor.white.cgColor
cardMaskLayer.backgroundColor = UIColor.clear.cgColor
drawerContentContainer.layer.mask = cardMaskLayer
maskDrawerVisualEffectView()
if !isAnimatingDrawerPosition || borderPath.boundingBox.height < drawerShadowView.layer.shadowPath?.boundingBox.height ?? 0.0
{
drawerShadowView.layer.shadowPath = borderPath
}
}
// MARK: Configuration Updates
/**
Set the drawer position, with an option to animate.
- parameter position: The position to set the drawer to.
- parameter animated: Whether or not to animate the change. (Default: true)
- parameter completion: A block object to be executed when the animation sequence ends. The Bool indicates whether or not the animations actually finished before the completion handler was called. (Default: nil)
*/
public func setDrawerPosition(position: PulleyPosition, animated: Bool, completion: PulleyAnimationCompletionBlock? = nil) {
guard supportedPositions.contains(position) else {
print("PulleyViewController: You can't set the drawer position to something not supported by the current view controller contained in the drawer. If you haven't already, you may need to implement the PulleyDrawerViewControllerDelegate.")
return
}
drawerPosition = position
var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight
var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultCollapsedHeight
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultPartialRevealHeight
}
let stopToMoveTo: CGFloat
switch drawerPosition {
case .collapsed:
stopToMoveTo = collapsedHeight
case .partiallyRevealed:
stopToMoveTo = partialRevealHeight
case .open:
stopToMoveTo = heightOfOpenDrawer
case .closed:
stopToMoveTo = 0
default:
stopToMoveTo = 0
}
let lowestStop = getStopList().min() ?? 0
triggerFeedbackGenerator()
if animated && self.view.window != nil
{
isAnimatingDrawerPosition = true
UIView.animate(withDuration: animationDuration, delay: animationDelay, usingSpringWithDamping: animationSpringDamping, initialSpringVelocity: animationSpringInitialVelocity, options: animationOptions, animations: { [weak self] () -> Void in
self?.drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false)
// Move backgroundDimmingView to avoid drawer background being darkened
self?.backgroundDimmingView.frame = self?.backgroundDimmingViewFrameForDrawerPosition(stopToMoveTo) ?? CGRect.zero
if let drawer = self
{
drawer.delegate?.drawerPositionDidChange?(drawer: drawer, bottomSafeArea: self?.pulleySafeAreaInsets.bottom ?? 0.0)
(drawer.drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer: drawer, bottomSafeArea: self?.pulleySafeAreaInsets.bottom ?? 0.0)
(drawer.primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer: drawer, bottomSafeArea: self?.pulleySafeAreaInsets.bottom ?? 0.0)
// Fix the bouncy drawer bug on iPad and Mac
if UIDevice.current.userInterfaceIdiom == .phone {
drawer.view.layoutIfNeeded()
}
}
}, completion: { [weak self] (completed) in
self?.isAnimatingDrawerPosition = false
self?.your_sha256_hash()
completion?(completed)
})
}
else
{
drawerScrollView.setContentOffset(CGPoint(x: 0, y: stopToMoveTo - lowestStop), animated: false)
// Move backgroundDimmingView to avoid drawer background being darkened
backgroundDimmingView.frame = backgroundDimmingViewFrameForDrawerPosition(stopToMoveTo)
delegate?.drawerPositionDidChange?(drawer: self, bottomSafeArea: pulleySafeAreaInsets.bottom)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerPositionDidChange?(drawer: self, bottomSafeArea: pulleySafeAreaInsets.bottom)
(primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerPositionDidChange?(drawer: self, bottomSafeArea: pulleySafeAreaInsets.bottom)
completion?(true)
}
}
/**
Set the drawer position, by default the change will be animated. Deprecated. Recommend switching to the other setDrawerPosition method, this one will be removed in a future release.
- parameter position: The position to set the drawer to.
- parameter isAnimated: Whether or not to animate the change. Default: true
*/
@available(*, deprecated)
public func setDrawerPosition(position: PulleyPosition, isAnimated: Bool = true)
{
setDrawerPosition(position: position, animated: isAnimated)
}
/**
Change the current primary content view controller (The one behind the drawer)
- parameter controller: The controller to replace it with
- parameter animated: Whether or not to animate the change. Defaults to true.
- parameter completion: A block object to be executed when the animation sequence ends. The Bool indicates whether or not the animations actually finished before the completion handler was called.
*/
public func setPrimaryContentViewController(controller: UIViewController, animated: Bool = true, completion: PulleyAnimationCompletionBlock?)
{
// Account for transition issue in iOS 11
controller.view.frame = primaryContentContainer.bounds
controller.view.layoutIfNeeded()
if animated
{
UIView.transition(with: primaryContentContainer, duration: animationDuration, options: .transitionCrossDissolve, animations: { [weak self] () -> Void in
self?.primaryContentViewController = controller
}, completion: { (completed) in
completion?(completed)
})
}
else
{
primaryContentViewController = controller
completion?(true)
}
}
/**
Change the current primary content view controller (The one behind the drawer). This method exists for backwards compatibility.
- parameter controller: The controller to replace it with
- parameter animated: Whether or not to animate the change. Defaults to true.
*/
public func setPrimaryContentViewController(controller: UIViewController, animated: Bool = true)
{
setPrimaryContentViewController(controller: controller, animated: animated, completion: nil)
}
/**
Change the current drawer content view controller (The one inside the drawer)
- parameter controller: The controller to replace it with
- parameter position: The initial position of the contoller
- parameter animated: Whether or not to animate the change.
- parameter completion: A block object to be executed when the animation sequence ends. The Bool indicates whether or not the animations actually finished before the completion handler was called.
*/
public func setDrawerContentViewController(controller: UIViewController, position: PulleyPosition? = nil, animated: Bool = true, completion: PulleyAnimationCompletionBlock?)
{
// Account for transition issue in iOS 11
controller.view.frame = drawerContentContainer.bounds
controller.view.layoutIfNeeded()
if animated
{
UIView.transition(with: drawerContentContainer, duration: animationDuration, options: .transitionCrossDissolve, animations: { [weak self] () -> Void in
self?.drawerContentViewController = controller
self?.setDrawerPosition(position: position ?? (self?.drawerPosition ?? .collapsed), animated: false)
}, completion: { (completed) in
completion?(completed)
})
}
else
{
drawerContentViewController = controller
setDrawerPosition(position: position ?? drawerPosition, animated: false)
completion?(true)
}
}
/**
Change the current drawer content view controller (The one inside the drawer). This method exists for backwards compatibility.
- parameter controller: The controller to replace it with
- parameter animated: Whether or not to animate the change.
- parameter completion: A block object to be executed when the animation sequence ends. The Bool indicates whether or not the animations actually finished before the completion handler was called.
*/
public func setDrawerContentViewController(controller: UIViewController, animated: Bool = true, completion: PulleyAnimationCompletionBlock?)
{
setDrawerContentViewController(controller: controller, position: nil, animated: animated, completion: completion)
}
/**
Change the current drawer content view controller (The one inside the drawer). This method exists for backwards compatibility.
- parameter controller: The controller to replace it with
- parameter animated: Whether or not to animate the change.
*/
public func setDrawerContentViewController(controller: UIViewController, animated: Bool = true)
{
setDrawerContentViewController(controller: controller, position: nil, animated: animated, completion: nil)
}
/**
Update the supported drawer positions allows by the Pulley Drawer
*/
public func setNeedsSupportedDrawerPositionsUpdate()
{
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
if let setSupportedDrawerPositions = drawerVCCompliant.supportedDrawerPositions?() {
supportedPositions = self.currentDisplayMode == .compact ? setSupportedDrawerPositions.filter(PulleyPosition.compact.contains) : setSupportedDrawerPositions
} else {
supportedPositions = self.currentDisplayMode == .compact ? PulleyPosition.compact : PulleyPosition.all
}
}
else
{
supportedPositions = self.currentDisplayMode == .compact ? PulleyPosition.compact : PulleyPosition.all
}
}
// MARK: Actions
@objc func dimmingViewTapRecognizerAction(gestureRecognizer: UITapGestureRecognizer)
{
if gestureRecognizer == dimmingViewTapRecognizer
{
if gestureRecognizer.state == .ended
{
self.setDrawerPosition(position: positionWhenDimmingBackgroundIsTapped, animated: true)
}
}
}
// MARK: Propogate child view controller style / status bar presentation based on drawer state
override open var childForStatusBarStyle: UIViewController? {
get {
if drawerPosition == .open {
return drawerContentViewController
}
return primaryContentViewController
}
}
override open var childForStatusBarHidden: UIViewController? {
get {
if drawerPosition == .open {
return drawerContentViewController
}
return primaryContentViewController
}
}
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if #available(iOS 10.0, *) {
coordinator.notifyWhenInteractionChanges { [weak self] context in
guard let currentPosition = self?.drawerPosition else { return }
self?.setDrawerPosition(position: currentPosition, animated: false)
}
} else {
coordinator.notifyWhenInteractionEnds { [weak self] context in
guard let currentPosition = self?.drawerPosition else { return }
self?.setDrawerPosition(position: currentPosition, animated: false)
}
}
}
// MARK: PulleyDrawerViewControllerDelegate implementation for nested Pulley view controllers in drawers. Implemented here, rather than an extension because overriding extensions in subclasses isn't good practice. Some developers want to subclass Pulley and customize these behaviors, so we'll move them here.
open func collapsedDrawerHeight(bottomSafeArea: CGFloat) -> CGFloat {
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate,
let collapsedHeight = drawerVCCompliant.collapsedDrawerHeight?(bottomSafeArea: bottomSafeArea) {
return collapsedHeight
} else {
return 68.0 + bottomSafeArea
}
}
open func partialRevealDrawerHeight(bottomSafeArea: CGFloat) -> CGFloat {
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate,
let partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight?(bottomSafeArea: bottomSafeArea) {
return partialRevealHeight
} else {
return 264.0 + bottomSafeArea
}
}
open func supportedDrawerPositions() -> [PulleyPosition] {
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate,
let supportedPositions = drawerVCCompliant.supportedDrawerPositions?() {
return (self.currentDisplayMode == .compact ? supportedPositions.filter(PulleyPosition.compact.contains) : supportedPositions)
} else {
return (self.currentDisplayMode == .compact ? PulleyPosition.compact : PulleyPosition.all)
}
}
open func drawerPositionDidChange(drawer: PulleyViewController, bottomSafeArea: CGFloat) {
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate {
drawerVCCompliant.drawerPositionDidChange?(drawer: drawer, bottomSafeArea: bottomSafeArea)
}
}
open func makeUIAdjustmentsForFullscreen(progress: CGFloat, bottomSafeArea: CGFloat) {
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate {
drawerVCCompliant.makeUIAdjustmentsForFullscreen?(progress: progress, bottomSafeArea: bottomSafeArea)
}
}
open func drawerChangedDistanceFromBottom(drawer: PulleyViewController, distance: CGFloat, bottomSafeArea: CGFloat) {
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate {
drawerVCCompliant.drawerChangedDistanceFromBottom?(drawer: drawer, distance: distance, bottomSafeArea: bottomSafeArea)
}
}
}
extension PulleyViewController: PulleyPassthroughScrollViewDelegate {
func shouldTouchPassthroughScrollView(scrollView: PulleyPassthroughScrollView, point: CGPoint) -> Bool
{
return !drawerContentContainer.bounds.contains(drawerContentContainer.convert(point, from: scrollView))
}
func viewToReceiveTouch(scrollView: PulleyPassthroughScrollView, point: CGPoint) -> UIView
{
if currentDisplayMode == .drawer
{
if drawerPosition == .open
{
return backgroundDimmingView
}
return primaryContentContainer
}
else
{
if drawerContentContainer.bounds.contains(drawerContentContainer.convert(point, from: scrollView))
{
return drawerContentViewController.view
}
return primaryContentContainer
}
}
}
extension PulleyViewController: UIScrollViewDelegate {
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if scrollView == drawerScrollView
{
// Find the closest anchor point and snap there.
var collapsedHeight:CGFloat = kPulleyDefaultCollapsedHeight
var partialRevealHeight:CGFloat = kPulleyDefaultPartialRevealHeight
if let drawerVCCompliant = drawerContentViewController as? PulleyDrawerViewControllerDelegate
{
collapsedHeight = drawerVCCompliant.collapsedDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultCollapsedHeight
partialRevealHeight = drawerVCCompliant.partialRevealDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultPartialRevealHeight
}
var drawerStops: [CGFloat] = [CGFloat]()
var currentDrawerPositionStop: CGFloat = 0.0
if supportedPositions.contains(.open)
{
drawerStops.append(heightOfOpenDrawer)
if drawerPosition == .open
{
currentDrawerPositionStop = drawerStops.last!
}
}
if supportedPositions.contains(.partiallyRevealed)
{
drawerStops.append(partialRevealHeight)
if drawerPosition == .partiallyRevealed
{
currentDrawerPositionStop = drawerStops.last!
}
}
if supportedPositions.contains(.collapsed)
{
drawerStops.append(collapsedHeight)
if drawerPosition == .collapsed
{
currentDrawerPositionStop = drawerStops.last!
}
}
let lowestStop = drawerStops.min() ?? 0
let distanceFromBottomOfView = lowestStop + lastDragTargetContentOffset.y
var currentClosestStop = lowestStop
for currentStop in drawerStops
{
if abs(currentStop - distanceFromBottomOfView) < abs(currentClosestStop - distanceFromBottomOfView)
{
currentClosestStop = currentStop
}
}
var closestValidDrawerPosition: PulleyPosition = drawerPosition
if abs(Float(currentClosestStop - heightOfOpenDrawer)) <= Float.ulpOfOne && supportedPositions.contains(.open)
{
closestValidDrawerPosition = .open
}
else if abs(Float(currentClosestStop - collapsedHeight)) <= Float.ulpOfOne && supportedPositions.contains(.collapsed)
{
closestValidDrawerPosition = .collapsed
}
else if supportedPositions.contains(.partiallyRevealed)
{
closestValidDrawerPosition = .partiallyRevealed
}
let snapModeToUse: PulleySnapMode = closestValidDrawerPosition == drawerPosition ? snapMode : .nearestPosition
switch snapModeToUse {
case .nearestPosition:
setDrawerPosition(position: closestValidDrawerPosition, animated: true)
case .nearestPositionUnlessExceeded(let threshold):
let distance = currentDrawerPositionStop - distanceFromBottomOfView
var positionToSnapTo: PulleyPosition = drawerPosition
if abs(distance) > threshold
{
if distance < 0
{
let orderedSupportedDrawerPositions = supportedPositions.sorted(by: { $0.rawValue < $1.rawValue }).filter({ $0 != .closed })
for position in orderedSupportedDrawerPositions
{
if position.rawValue > drawerPosition.rawValue
{
positionToSnapTo = position
break
}
}
}
else
{
let orderedSupportedDrawerPositions = supportedPositions.sorted(by: { $0.rawValue > $1.rawValue }).filter({ $0 != .closed })
for position in orderedSupportedDrawerPositions
{
if position.rawValue < drawerPosition.rawValue
{
positionToSnapTo = position
break
}
}
}
}
setDrawerPosition(position: positionToSnapTo, animated: true)
}
}
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if scrollView == drawerScrollView {
self.isChangingDrawerPosition = true
}
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
prepareFeedbackGenerator()
if scrollView == drawerScrollView
{
lastDragTargetContentOffset = targetContentOffset.pointee
// Halt intertia
targetContentOffset.pointee = scrollView.contentOffset
self.isChangingDrawerPosition = false
}
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == drawerScrollView
{
let partialRevealHeight: CGFloat = (drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.partialRevealDrawerHeight?(bottomSafeArea: pulleySafeAreaInsets.bottom) ?? kPulleyDefaultPartialRevealHeight
let lowestStop = getStopList().min() ?? 0
if (scrollView.contentOffset.y - pulleySafeAreaInsets.bottom) > partialRevealHeight - lowestStop && supportedPositions.contains(.open)
{
// Calculate percentage between partial and full reveal
let fullRevealHeight = heightOfOpenDrawer
let progress: CGFloat
if fullRevealHeight == partialRevealHeight {
progress = 1.0
} else {
progress = (scrollView.contentOffset.y - (partialRevealHeight - lowestStop)) / (fullRevealHeight - (partialRevealHeight))
}
delegate?.makeUIAdjustmentsForFullscreen?(progress: progress, bottomSafeArea: pulleySafeAreaInsets.bottom)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: progress, bottomSafeArea: pulleySafeAreaInsets.bottom)
(primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: progress, bottomSafeArea: pulleySafeAreaInsets.bottom)
backgroundDimmingView.alpha = progress * backgroundDimmingOpacity
backgroundDimmingView.isUserInteractionEnabled = true
}
else
{
if backgroundDimmingView.alpha >= 0.001
{
backgroundDimmingView.alpha = 0.0
delegate?.makeUIAdjustmentsForFullscreen?(progress: 0.0, bottomSafeArea: pulleySafeAreaInsets.bottom)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: 0.0, bottomSafeArea: pulleySafeAreaInsets.bottom)
(primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.makeUIAdjustmentsForFullscreen?(progress: 0.0, bottomSafeArea: pulleySafeAreaInsets.bottom)
backgroundDimmingView.isUserInteractionEnabled = false
}
}
delegate?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom)
(drawerContentViewController as? PulleyDrawerViewControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom)
(primaryContentViewController as? PulleyPrimaryContentControllerDelegate)?.drawerChangedDistanceFromBottom?(drawer: self, distance: scrollView.contentOffset.y + lowestStop, bottomSafeArea: pulleySafeAreaInsets.bottom)
// Move backgroundDimmingView to avoid drawer background beeing darkened
backgroundDimmingView.frame = backgroundDimmingViewFrameForDrawerPosition(scrollView.contentOffset.y + lowestStop)
your_sha256_hash()
}
}
}
``` | /content/code_sandbox/PulleyLib/PulleyViewController.swift | swift | 2016-07-08T21:57:00 | 2024-08-10T19:44:06 | Pulley | 52inc/Pulley | 2,009 | 15,471 |
```qmake
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in D:\0_0DevTools\Android\sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# path_to_url
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
``` | /content/code_sandbox/jgraph/proguard-rules.pro | qmake | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 143 |
```java
package com.jonas.jgraph.inter;
/**
* @author yun.
* @date 2016/7/17
* @des []
* @since [path_to_url
* <p><a href="path_to_url">github</a>
*/
public interface OnGraphItemListener {
void onItemClick(int position);
void onItemLongClick(int position);
}
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/inter/OnGraphItemListener.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 78 |
```java
package com.jonas.jgraph.inter;
import com.jonas.jgraph.models.Jchart;
import java.util.List;
/**
* @author yun.
* @date 2016/6/8
* @des []
* @since [path_to_url
* <p><a href="path_to_url">github</a>
*/
public interface IChart {
/**
*
*/
public void cmdFill(Jchart... jcharts);
/**
*
*/
public void cmdFill(List<Jchart> jchartList);
}
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/inter/IChart.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 114 |
```java
package com.jonas.jgraph.graph;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.Shader;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import com.jonas.jgraph.inter.BaseGraph;
import com.jonas.jgraph.models.Jchart;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author yun.
* @date 2016/7/11
* @des []
* @since [path_to_url
* <p><a href="path_to_url">github</a>
*/
public class MultiGraph extends BaseGraph {
private int mWidth;
private int mHeight;
/**
* x y
*/
private float mHCoordinate = 0;
/**
* x x
*/
private float mAbove;
/**
*
*/
private Paint mExecelPaint;
private Paint mTextPaint;
/**
*
*/
private int mSelected = -1;
private float mDownX;
private boolean moved;
private Paint mLinePaint;
private Paint mDashLinePaint;
//
private float mTextMarging;
private float mTextSize = 15;
// private float mSugHeightest;
private Jchart mHeightestExcel;
private float mHeightRatio;
/**
*
*/
private int mAbscissaMsgColor = Color.parseColor("#556A73");
/**
*
*/
private int[] mShaderColors;
private Paint mTextBgPaint;
private int mTextBgColor = Color.parseColor("#556A73");
private int mTextColor = Color.WHITE;
private Rect mBounds;
private boolean mScrollAble = true;
private int mLineColor = Color.parseColor("#ffe9d1ba");
private Paint mPointPaint;
private int mPointColor = Color.parseColor("#CC6500");
private float mAbscissaMsgSize;
/**
*
*/
private Paint mAbscissaPaint;
private int mFixedNums;//
/**
*
*/
private float mLinePointRadio;
private float tempTextMargin;
private boolean lineFirstMoved = false;
private Paint mCoordinatePaint;
private float phase = 1;
private int mPading;
public interface ChartStyle {
/**
*
*/
int BAR = 1;
int LINE = 2;
int BAR_LINE = 3;
}
// public static class Jchart {
// private String mShowMsg;
// private int index;
// private float mWidth;//
// private float mHeight;//y
// private PointF mStart = new PointF();//
// private float mMidX;// x
// private int mColor;
// private float mNum; //
// private float mMax; //
// private String textMsg; //
// private String mXmsg; //
// private float mUpper;
// private float mLower;
// /**
// *
// */
// private String unit;
//
// public Jchart(float num, String mXmsg, int index) {
// this(0, num, mXmsg);
// this.index = index;
// }
//
// public Jchart(float num, String mXmsg) {
// this(0, num, mXmsg);
// }
//
// public Jchart(float lower, float upper, String mXmsg) {
// this(lower, upper, mXmsg, Color.GRAY);
// }
//
//
// public Jchart(float lower, float upper, String mXmsg, int color) {
// this(lower, upper, "", mXmsg, Color.GRAY);
// }
//
//
// public Jchart(float num, String unit, String mXmsg) {
// this(0, num, unit, mXmsg, Color.GRAY);
// }
//
//
// public Jchart(float lower, float upper, String unit, String mXmsg, int color) {
// mUpper = upper;
// mLower = lower;
// mHeight = mNum = upper - lower;
// mStart.y = mLower;
// this.mXmsg = mXmsg;
// this.unit = unit;
// this.mColor = color;
// mShowMsg = new DecimalFormat("##").format(mHeight);
// }
//
// public RectF getRectF() {
// return new RectF(mStart.x, mStart.y - mHeight, mStart.x + mWidth, mStart.y);
// }
//
//
// public PointF getMidPointF() {
// return new PointF(getMidX(), mStart.y - mHeight);
// }
//
//
// public String getTextMsg() {
// return textMsg;
// }
//
//
// public String getUnit() {
// return unit;
// }
//
//
// public void setUnit(String unit) {
// this.unit = unit;
// }
//
//
// public void setTextMsg(String textMsg) {
// this.textMsg = textMsg;
// }
//
//
// public float getWidth() {
// return mWidth;
// }
//
//
// public void setWidth(float width) {
// this.mWidth = width;
// }
//
//
// public float getHeight() {
// return mHeight;
// }
//
//
// public void setHeight(float height) {
// this.mHeight = height;
// }
//
//
// public PointF getStart() {
// return mStart;
// }
//
//
// public void setStart(PointF start) {
// this.mStart = start;
// }
//
//
// public float getMidX() {
// if (null != mStart) {
// mMidX = mStart.x + mWidth / 2;
// } else {
// throw new RuntimeException("mStart ");
// }
// return mMidX;
// }
//
//
// public void setMidX(float midX) {
// this.mMidX = midX;
// }
//
//
// public int getColor() {
// return mColor;
// }
//
//
// public void setColor(int color) {
// mColor = color;
// }
//
//
// public float getNum() {
// return mNum;
// }
//
//
// public void setNum(float num) {
// this.mNum = num;
// }
//
//
// public float getMax() {
// return mMax;
// }
//
//
// public void setMax(float max) {
// this.mMax = max;
// }
//
//
// public String getXmsg() {
// return mXmsg;
// }
//
//
// public void setXmsg(String xmsg) {
// this.mXmsg = xmsg;
// }
//
//
// public float getUpper() {
// return mUpper;
// }
//
//
// public void setUpper(float upper) {
// mUpper = upper;
// mHeight = mUpper - mLower;
// mShowMsg = new DecimalFormat("##.#").format(mUpper);
// }
//
//
// public float getLower() {
// return mLower;
// }
//
//
// public void setLower(float lower) {
// mLower = lower;
// }
//
// public int getIndex() {
// return index;
// }
//
// public void setIndex(int index) {
// this.index = index;
// }
//
// public String getShowMsg() {
// return mShowMsg;
// }
//
// public void setShowMsg(String showMsg) {
// mShowMsg = showMsg;
// }
// }
private Context mContext;
/**
*
*/
private int mTouchSlop;
/**
*
*/
private float mInterval;
/**
*
*/
private List<Jchart> mExcels = new ArrayList<>();
/**
*
*/
private int mActivationColor = Color.RED;
/**
*
*/
private int mNormalColor = Color.DKGRAY;
/**
*
*/
private int mChartStyle = ChartStyle.LINE;
/**
*
*/
private float mSliding = 0;
/**
*
*/
private float mBarWidth = 0;
private Path pathLine = new Path();
public MultiGraph(Context context) {
super(context);
init(context);
}
public MultiGraph(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MultiGraph(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
protected void init(Context context) {
mContext = context;
initData();
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mExecelPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTextAlign(Paint.Align.CENTER);
mTextPaint.setTextSize(mTextSize);
mTextBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPointPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mAbscissaPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextBgPaint.setColor(mTextBgColor);
mAbscissaPaint.setTextSize(mAbscissaMsgSize);
mAbscissaPaint.setColor(mAbscissaMsgColor);
mAbscissaPaint.setTextAlign(Paint.Align.CENTER);
mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mLinePaint.setStrokeWidth(2);
mLinePaint.setStyle(Paint.Style.STROKE);// style Paint.Style.STROKE
mDashLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mDashLinePaint.setStrokeWidth(2);
mDashLinePaint.setStyle(Paint.Style.STROKE);// style Paint.Style.STROKE
mCoordinatePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
// mCoordinatePaint.setStrokeWidth(dip2px(2));
mCoordinatePaint.setStyle(Paint.Style.STROKE);
}
/**
*
*/
private void initData() {
mBarWidth = dip2px(36);
mInterval = dip2px(20);
tempTextMargin = mTextMarging = dip2px(3);
mTextSize = sp2px(12);
mAbscissaMsgSize = sp2px(12);
mBounds = new Rect();
mLinePointRadio = dip2px(4);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mHeight = h;
mHCoordinate = mHeight - Math.abs(2 * mAbscissaMsgSize);
if (mChartStyle == ChartStyle.LINE) {
mTextMarging *= 2;
}
// mPading = dip2px(15);
mPading = 0;
refreshBarWidth_Interval(w);
if (mExcels.size() > 0) {
refreshExcels();
}
mWidth = w;
}
private void refreshBarWidth_Interval(int w) {
if (!mScrollAble) {
if (mFixedNums > 0 && mChartStyle == ChartStyle.BAR) {
mBarWidth = (w - 2 * mPading - 2 * (mFixedNums + 1)) / ((float) mFixedNums);
mInterval = (w - 2 * mPading - mBarWidth * mExcels.size()) / (mExcels.size() + 1);
} else {
mInterval = 2;
mBarWidth = (w - 2 * mPading - mInterval * (mExcels.size() - 1)) / mExcels.size();
}
}
}
protected void refreshExcels() {
if (mHCoordinate > 0) {
mHeightRatio = (mHCoordinate - 2 * mTextSize - mAbove - mTextMarging - mLinePointRadio * 2) / mHeightestExcel.getHeight();
for (int i = 0; i < mExcels.size(); i++) {
Jchart jchart = mExcels.get(i);
jchart.setHeight(jchart.getHeight() * mHeightRatio);
jchart.setWidth(mBarWidth);
PointF start = jchart.getStart();
if (mFixedNums > 0 && mChartStyle == ChartStyle.BAR) {
start.x = mPading + mInterval * (i + 1) + mBarWidth * i;
} else {
start.x = mPading + mInterval * i + mBarWidth * i;
}
start.y = mHCoordinate - mAbove - jchart.getLower();
jchart.setColor(mNormalColor);
}
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (null != mExcels && mExcels.size() > 0) {
if (mChartStyle == ChartStyle.BAR) {
drawSugExcel_BAR(canvas);
} else if (mChartStyle == ChartStyle.LINE) {
drawSugExcel_LINE(canvas);
} else {
drawSugExcel_BAR(canvas);
drawSugExcel_LINE(canvas);
}
}
drawCoordinateAxes(canvas);
}
protected void drawSugExcel_BAR(Canvas canvas) {
for (int i = 0; i < mExcels.size(); i++) {
Jchart excel = mExcels.get(i);
PointF start = excel.getStart();
start.x += mSliding;
if (null != mShaderColors) {
mExecelPaint.setShader(new LinearGradient(start.x, start.y - excel.getHeight
(), start.x, start.y, mShaderColors[0], mShaderColors[1], Shader
.TileMode
.CLAMP));
}
if (i != mSelected) {
if (null == mShaderColors) {
mExecelPaint.setColor(mNormalColor);
}
} else {
if (null == mShaderColors) {
mExecelPaint.setColor(mActivationColor);
}
}
if (excel.getHeight() > 0) {
canvas.drawRect(excel.getRectF(), mExecelPaint);
}
drawAbscissaMsg(canvas, excel);
}
if (mSelected > -1) {
drawSelectedText(canvas, mExcels.get(mSelected));
} else {
drawSelectedText(canvas, mExcels.get(mHeightestExcel.getIndex()));
}
}
protected void drawAbscissaMsg(Canvas canvas, Jchart excel) {
if (null != excel) {
mAbscissaPaint.setColor(mAbscissaMsgColor);
PointF midPointF = excel.getMidPointF();
if (!TextUtils.isEmpty(excel.getXmsg())) {
String xmsg = excel.getXmsg();
float w = mAbscissaPaint.measureText(xmsg, 0, xmsg.length());
if (midPointF.x - w / 2 < 0) {
canvas.drawText(excel.getXmsg(), w / 2, mHCoordinate + dip2px(3) + mTextSize, mAbscissaPaint);
} else if (midPointF.x + w / 2 > mWidth) {
canvas.drawText(excel.getXmsg(), mWidth - w / 2, mHCoordinate + dip2px(3) + mTextSize, mAbscissaPaint);
} else {
canvas.drawText(excel.getXmsg(), midPointF.x, mHCoordinate + dip2px(3) + mTextSize, mAbscissaPaint);
}
}
}
}
// private void drawSelectedText(Canvas canvas, Jchart excel) {
//
// mTextPaint.setColor(mTextColor);
// PointF midPointF = excel.getMidPointF();
//// String msg = excel.getUpper() + excel.getUnit();
// String msg = excel.getShowMsg();
// mTextPaint.getTextBounds(msg, 0, msg.length(), mBounds);
// Path textBg = new Path();
//
// float bgHeight = dip2px(6);
// float bgWidth = dip2px(8);
// if (mGraphStyle == GraphStyle.LINE) {
// mTextMarging = tempTextMargin + mLinePointRadio;
// } else {
// mTextMarging = tempTextMargin;
// }
// textBg.moveTo(midPointF.x, midPointF.y - mTextMarging);
// textBg.lineTo(midPointF.x - bgWidth / 2, midPointF.y - mTextMarging - bgHeight - 1.5f);
// textBg.lineTo(midPointF.x + bgWidth / 2, midPointF.y - mTextMarging - bgHeight - 1.5f);
// textBg.close();
// canvas.drawPath(textBg, mTextBgPaint);
//
// RectF rectF = new RectF(midPointF.x - mBounds.width() / 2f - bgWidth, midPointF.y - mTextMarging - bgHeight - mBounds.height() - bgHeight * 2f
// , midPointF.x + mBounds.width() / 2f + bgWidth, midPointF.y - mTextMarging - bgHeight);
// float dffw = rectF.right - mWidth;
// float msgX = midPointF.x;
// float magin = 1;
// if (dffw > 0) {
// rectF.right = rectF.right - dffw - magin;
// rectF.left = rectF.left - dffw - magin;
// msgX = midPointF.x - dffw - magin;
// } else if (rectF.left < 0) {
// rectF.right = rectF.right - rectF.left + magin;
// msgX = midPointF.x - rectF.left + magin;
// rectF.left = magin;
// }
// canvas.drawRoundRect(rectF, 3, 3, mTextBgPaint);
// canvas.drawText(msg, msgX, midPointF.y - mTextMarging - bgHeight * 2, mTextPaint);
// }
/**
*
*/
private List<Path> mPathList = new ArrayList<>();
/**
*
*/
private List<Path> mDashPathList = new ArrayList<>();
/**
*
*/
protected void drawSugExcel_LINE(Canvas canvas) {
pathLine.reset();
mLinePaint.setColor(mLineColor);
mDashLinePaint.setColor(mLineColor);
mPointPaint.setColor(mPointColor);
if (arrangeLineDate(canvas)) return;
arrangeDashLineDate(canvas);
for (Path path : mDashPathList) {
DashPathEffect effect = new DashPathEffect(new float[]{8, 5}, phase);
mDashLinePaint.setPathEffect(effect);
canvas.drawPath(path, mDashLinePaint);
}
if (mLinePointRadio > 0) {
for (Jchart excel : mExcels) {
if (excel.getHeight() > 0) {
PointF midPointF = excel.getMidPointF();
canvas.drawCircle(midPointF.x, midPointF.y, mLinePointRadio, mPointPaint);
// mCoordinatePaint.setColor(Color.parseColor("#ffffffff"));
mCoordinatePaint.setColor(0Xffffffff);
mCoordinatePaint.setStrokeWidth(dip2px(2));
canvas.drawCircle(midPointF.x, midPointF.y, mLinePointRadio, mCoordinatePaint);
}
}
}
if (mSelected > -1) {
drawSelectedText(canvas, mExcels.get(mSelected));
} else {
drawSelectedText(canvas, mExcels.get(mHeightestExcel.getIndex()));
}
if (mDashPathList.size() > 0) {
phase = ++phase % 50;
postInvalidateDelayed(50);
}
}
private void arrangeDashLineDate(Canvas canvas) {
lineFirstMoved = false;
mDashPathList.clear();
for (int i = 0; i < mPathList.size(); i++) {
Path path = mPathList.get(i);
PathMeasure pathMeasure = new PathMeasure(path, false);
float length = pathMeasure.getLength();
float[] post = new float[2];
pathMeasure.getPosTan(0, post, null);
float[] post_end = new float[2];
pathMeasure.getPosTan(length, post_end, null);
if (length > 0.001f) {
canvas.drawPath(path, mLinePaint);
path.lineTo(post_end[0], mHCoordinate);
path.lineTo(post[0], mHCoordinate);//
path.close();
mExecelPaint.setShader(new LinearGradient(0, 0, 0, mHCoordinate, mShaderColors[0], mShaderColors[1], Shader
.TileMode
.CLAMP));
canvas.drawPath(path, mExecelPaint);
} else {
post_end[0] = post[0];
post_end[1] = post[1];
}
if (i < mPathList.size() - 1) {
path = new Path();
path.moveTo(post_end[0], post_end[1]);
PathMeasure pathMeasuredotted = new PathMeasure(mPathList.get(i + 1), false);
pathMeasuredotted.getPosTan(0, post, null);
path.lineTo(post[0], post[1]);
mDashPathList.add(path);
}
}
}
private boolean arrangeLineDate(Canvas canvas) {
Path pathline = null;
mPathList.clear();
for (int i = 0; i < mExcels.size(); i++) {
if (!lineFirstMoved) {
pathline = new Path();
}
Jchart excel = null;
if (pathline != null) {
excel = mExcels.get(i);
if (null == excel) {
return true;
}
PointF start = excel.getStart();
if (mChartStyle == ChartStyle.LINE) {
start.x += mSliding;
}
PointF midPointF = excel.getMidPointF();
if (excel.getHeight() > 0) {
if (!lineFirstMoved) {
pathline.moveTo(midPointF.x, midPointF.y);
lineFirstMoved = true;
} else {
pathline.lineTo(midPointF.x, midPointF.y);
}
} else {
if (!pathline.isEmpty()) {
PathMeasure pathMeasure = new PathMeasure(pathline, false);
if (i > 0 && pathMeasure.getLength() < 0.001f) {
PointF midPointFpre = mExcels.get(i - 1).getMidPointF();
pathline.lineTo(midPointFpre.x, midPointFpre.y + 0.001f);
}
mPathList.add(pathline);
}
lineFirstMoved = false;
}
if (i == mExcels.size() - 1 && lineFirstMoved) {
PathMeasure pathMeasure = new PathMeasure(pathline, false);
if (i > 0 && pathMeasure.getLength() < 0.001f) {
pathline.lineTo(midPointF.x, midPointF.y + 0.001f);
}
mPathList.add(pathline);
}
}
drawAbscissaMsg(canvas, excel);
}
return false;
}
/**
*
*/
protected void drawCoordinateAxes(Canvas canvas) {
mCoordinatePaint.setColor(Color.parseColor("#AFAFB0"));
mCoordinatePaint.setStrokeWidth(2);
canvas.drawLine(0, mHCoordinate, mWidth, mHCoordinate, mCoordinatePaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mExcels.size() > 0) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownX = event.getX();
break;
case MotionEvent.ACTION_MOVE:
if (mScrollAble) {
float moveX = event.getX();
mSliding = moveX - mDownX;
if (Math.abs(mSliding) > mTouchSlop) {
moved = true;
mDownX = moveX;
if (mExcels.get(0).getStart().x + mSliding > mInterval ||
mExcels.get(mExcels.size() - 1).getStart().x + mBarWidth + mInterval + mSliding <
mWidth) {
return true;
}
invalidate();
}
} else {
PointF tup = new PointF(event.getX(), event.getY());
mSelected = clickWhere(tup);
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (!moved) {
PointF tup = new PointF(event.getX(), event.getY());
mSelected = clickWhere(tup);
invalidate();
}
moved = false;
mSliding = 0;
break;
default:
break;
}
}
return true;
}
/**
*
*/
public void feedData(Jchart... jcharts) {
feedData(Arrays.asList(jcharts));
}
/**
*
*/
public void feedData(List<Jchart> jchartList) {
lineFirstMoved = false;
mSelected = -1;
mExcels.clear();
if (jchartList != null && jchartList.size() > 0) {
mHeightestExcel = jchartList.get(0);
for (Jchart jchart : jchartList) {
mHeightestExcel = mHeightestExcel.getHeight() > jchart.getHeight() ? mHeightestExcel : jchart;
}
for (int i = 0; i < jchartList.size(); i++) {
Jchart jchart = jchartList.get(i);
jchart.setWidth(mBarWidth);
PointF start = jchart.getStart();
start.x = mInterval * (i + 1) + mBarWidth * i;
jchart.setColor(mNormalColor);
mExcels.add(jchart);
}
if (mWidth > 0) {
//
if (!mScrollAble) {
if (mFixedNums > 0 && mChartStyle == ChartStyle.BAR) {
mBarWidth = (mWidth - 2 * (mFixedNums + 1)) * 1f / mFixedNums;
mInterval = (mWidth - mBarWidth * mExcels.size()) / (mExcels.size() + 1);
} else {
mInterval = 2;
mBarWidth = (mWidth - mInterval * (mExcels.size() - 1)) / mExcels.size();
}
}
refreshExcels();
}
}
postInvalidate();
}
public float getInterval() {
return mInterval;
}
/**
*
*/
public void setInterval(float interval) {
this.mInterval = interval;
}
public int getNormalColor() {
return mNormalColor;
}
/**
*
*/
public void setNormalColor(int normalColor) {
mNormalColor = normalColor;
mLineColor = normalColor;
}
public int getActivationColor() {
return mActivationColor;
}
/**
*
*/
public void setActivationColor(int activationColor) {
mActivationColor = activationColor;
}
public int getGraphStyle() {
return mChartStyle;
}
/**
* +
*/
public void setGraphStyle(int graphStyle) {
mChartStyle = graphStyle;
}
/**
* -
*/
public float getSliding() {
return mExcels.get(0).getStart().x - mInterval;
}
public void setSliding(float sliding) {
mSliding = sliding;
}
public float getBarWidth() {
return mBarWidth;
}
/**
*
*/
public void setBarWidth(float barWidth) {
mBarWidth = dip2px(barWidth);
}
public float getTextSize() {
return mTextSize;
}
/**
* x ()
*/
public void setTextSize(float textSize) {
mTextSize = sp2px(textSize);
mHCoordinate = mTextSize * 2;
mTextPaint.setTextSize(mTextSize);
}
public float getAbscissaMsgSize() {
return mAbscissaMsgSize;
}
public void setAbscissaMsgSize(float abscissaMsgSize) {
mAbscissaMsgSize = abscissaMsgSize;
mAbscissaPaint.setTextSize(dip2px(mAbscissaMsgSize));
mHCoordinate = mHeight - Math.abs(2 * mAbscissaMsgSize);
refreshExcels();
}
public int getTextBgColor() {
return mTextBgColor;
}
public void setTextBgColor(int textBgColor) {
mTextBgColor = textBgColor;
mTextBgPaint.setColor(mTextBgColor);
}
public int getAbscissaMsgColor() {
return mAbscissaMsgColor;
}
public void setAbscissaMsgColor(int abscissaMsgColor) {
mAbscissaMsgColor = abscissaMsgColor;
mAbscissaPaint.setColor(mAbscissaMsgColor);
}
public float getTextMarging() {
return mTextMarging;
}
public void setTextMarging(float textMarging) {
tempTextMargin = mTextMarging = dip2px(textMarging);
}
public float getHCoordinate() {
return mHCoordinate;
}
/**
*
*
* @param colors
*/
public void setExecelPaintShaderColors(int... colors) {
mShaderColors = colors;
}
/**
* x
*
* @param HCoordinate
*/
public void setHCoordinate(float HCoordinate) {
mHCoordinate = HCoordinate;
}
/**
*
*
* @param scrollAble
*/
public void setScrollAble(boolean scrollAble) {
mScrollAble = scrollAble;
}
/**
* /
*
*
* @param fixedNums
*/
public void setFixedWidth(int fixedNums) {
mScrollAble = false;
mFixedNums = fixedNums;
}
public float getLinePointRadio() {
return mLinePointRadio;
}
/**
*
*
* @param linePointRadio
*/
public void setLinePointRadio(float linePointRadio) {
mLinePointRadio = dip2px(linePointRadio);
}
public void setPointColor(int pointColor) {
mPointColor = pointColor;
}
public void setLineWidth(int width) {
mLinePaint.setStrokeWidth(dip2px(width));
mDashLinePaint.setStrokeWidth(dip2px(width));
}
public void setLineColor(int color) {
mLineColor = color;
}
public int dip2px(float dipValue) {
final float scale = mContext.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
/**
* sppx
*
* @param spValue DisplayMetricsscaledDensity
*/
public int sp2px(float spValue) {
final float fontScale = mContext.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
}
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/graph/MultiGraph.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 6,962 |
```java
package com.jonas.jgraph.inter;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.BounceInterpolator;
import android.widget.Scroller;
import com.jonas.jgraph.BuildConfig;
import com.jonas.jgraph.R;
import com.jonas.jgraph.models.Jchart;
import com.jonas.jgraph.utils.CalloutHelper;
import com.jonas.jgraph.utils.MathHelper;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @author yun.
* @date 2016/7/11
* @des [ finish ]
* @since [path_to_url
* <p><a href="path_to_url">github</a>
*/
public abstract class BaseGraph extends View implements GestureDetector.OnGestureListener {
private static final String TAG = BaseGraph.class.getSimpleName();
/**
*
*/
protected int mSelected = -1;
protected int mHeight;
protected int mWidth;
protected Paint mCoordinatePaint;
/**
*
*/
protected Paint mAbscissaPaint;
protected Paint mAbscisDashPaint;
protected Paint mSelectedTextBgPaint;
protected Paint mSelectedTextPaint;
protected boolean mNeedY_abscissMasg = true;
/**
*
*/
protected ArrayList<String> mYaxis_msg;
protected float mYaxis_Max = 0;
protected float mYaxis_min;
/**
* y
*/
protected String mYaxismax = "100";
/**
*
*/
private float mAllowError = 3;
protected float mAbscisDashLineWidth = 0.5f;
/**
*
*/
protected float mChartRithtest_x;
protected float mChartLeftest_x;
/**
*
*/
protected float mCharAreaWidth;
private float mHeightRatio;
/**
* x
*/
protected RectF mChartArea;
/**
*
*/
protected float mBgTriangleHeight;
protected float mBarWidth = -1;
/**
*
*/
protected float mSelectedTextMarging = 4;
protected ArrayList<PointF> mAllPoints = new ArrayList<>();
/**
*
*/
protected float mInterval = 0;
/**
*
*/
private int mAbove;
/**
*
*/
protected boolean mScrollAble;
/**
*
*/
protected PointF mCenterPoint;
/**
* (()/())
* <p> mVisibleNumsmchart</p>
* <p> mVisibleNumsmchart</p>
*/
protected int mVisibleNums = 0;
/**
*
* <p color="red">mVisibleNums>=mExecels.size
*/
// protected boolean mForceFixNums;
/**
* -1
*/
protected int mSelectedMode = -1;
/**
*
*/
protected Jchart mHeightestChart;
protected Jchart mMinestChart;
protected Jchart mLastJchart;
protected Jchart mFirstJchart;
/**
*
*/
private int mAbscissaMsgSize;
protected int mState = 0;
private int mXNums;
private int mXinterval;
private GestureDetector mGestureDetector;
private Scroller mScroller;
private int mMinimumVelocity;
private int mMaximumVelocity;
private float upPlace;
private OnGraphItemListener mListener;
public final static int SELECETD_NULL = -1;
/**
*
*/
public final static int SELECTED_ACTIVATED = 0;
/**
*
*/
public final static int SELECETD_MSG_SHOW_TOP = 1;
@Retention(RetentionPolicy.SOURCE)
@IntDef({SELECETD_NULL, SELECTED_ACTIVATED, SELECETD_MSG_SHOW_TOP})
public @interface SelectedMode {}
public final static int aniChange = 1;
public final static int aniShow = 2;
public final static int aniFinish = 3;
@Retention(RetentionPolicy.SOURCE)
@IntDef({aniChange, aniShow, aniFinish})
protected @interface State {}
public final static int BAR = 0;
public final static int LINE = 1;
@Retention(RetentionPolicy.SOURCE)
@IntDef({BAR, LINE})
public @interface GraphStyle {}
protected Context mContext;
/**
*
*/
protected int mTouchSlop;
/**
*
*/
protected List<Jchart> mJcharts = new ArrayList<>();
/**
*
*/
protected int mActivationColor = Color.RED;
/**
*
*/
protected int mNormalColor = Color.DKGRAY;
/**
*
*/
protected int mGraphStyle = LINE;
/**
*
*/
protected float mSliding = 0;
/**
*
*/
protected float mPhase = 3;
/**
* /
*/
protected ArrayList<PointF> mAllLastPoints = new ArrayList<>();
protected ValueAnimator mValueAnimator = new ValueAnimator();
/**
* AccelerateInterpolator()
* DecelerateInterpolator()
* AccelerateDecelerateInterpolator()
* AnticipateInterpolator()
* OvershootInterpolator()
* AnticipateOvershootInterpolator()
* BounceInterpolator()
* LinearInterpolator()
*/
private TimeInterpolator mInterpolator = new BounceInterpolator();
private static final long ANIDURATION = 1100;
public BaseGraph(Context context){
this(context, null);
}
public BaseGraph(Context context, AttributeSet attrs){
this(context, attrs, 0);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AndroidJgraph);
mGraphStyle = a.getInt(R.styleable.AndroidJgraph_graphstyle, LINE);
mScrollAble = a.getBoolean(R.styleable.AndroidJgraph_scrollable, false);
mNeedY_abscissMasg = a.getBoolean(R.styleable.AndroidJgraph_showymsg, true);
mNormalColor = a.getColor(R.styleable.AndroidJgraph_normolcolor, Color.parseColor("#676567"));
mActivationColor = a.getColor(R.styleable.AndroidJgraph_activationcolor, Color.RED);
mVisibleNums = a.getInt(R.styleable.AndroidJgraph_visiblenums, 0);
a.recycle();
}
public BaseGraph(Context context, AttributeSet attrs, int defStyleAttr){
super(context, attrs, defStyleAttr);
init(context);
}
protected void init(Context context){
mContext = context;
mTouchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop();
mCoordinatePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCoordinatePaint.setStyle(Paint.Style.STROKE);
mCoordinatePaint.setColor(Color.parseColor("#AFAFB0"));
mCoordinatePaint.setStrokeWidth(1f);
mAbscissaPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mAbscissaPaint.setTextAlign(Paint.Align.CENTER);
mAbscissaMsgSize = MathHelper.dip2px(mContext, 12);
mAbscissaPaint.setTextSize(mAbscissaMsgSize);
mAbscissaPaint.setColor(Color.parseColor("#556A73"));
//
mAbscisDashPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mAbscisDashPaint.setStrokeWidth(mAbscisDashLineWidth);
mAbscisDashPaint.setStyle(Paint.Style.STROKE);
mAbscisDashPaint.setColor(Color.parseColor("#556A73"));
mSelectedTextBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
//
mSelectedTextBgPaint.setColor(Color.GRAY);
mBgTriangleHeight = MathHelper.dip2px(mContext, 6);
mSelectedTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
//
mSelectedTextPaint.setTextAlign(Paint.Align.CENTER);
mSelectedTextPaint.setColor(Color.WHITE);
mSelectedTextPaint.setTextSize(MathHelper.dip2px(mContext, 12));
mBarWidth = MathHelper.dip2px(mContext, 10);//
mInterval = MathHelper.dip2px(mContext, 4);//
}
@Override
protected void onFinishInflate(){
super.onFinishInflate();
mGestureDetector = new GestureDetector(mContext, this);
mScroller = new Scroller(mContext);
ViewConfiguration viewConfiguration = ViewConfiguration.get(mContext);
mMinimumVelocity = viewConfiguration.getScaledMinimumFlingVelocity();
mMaximumVelocity = viewConfiguration.getScaledMaximumFlingVelocity();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh){
super.onSizeChanged(w, h, oldw, oldh);
mHeight = h-getPaddingBottom()-getPaddingTop();
mWidth = w-getPaddingLeft()-getPaddingRight();
mCenterPoint = new PointF(w/2f, h/2f);
if(mGraphStyle == BAR || mGraphStyle == LINE) {
refreshChartArea();
}
}
/**
*
*/
protected void refreshChartArea(){
float yMsgLength = 0;
float yMsgHeight = 0;
Rect bounds = new Rect();
mAbscissaPaint.getTextBounds(mYaxismax, 0, mYaxismax.length(), bounds);
if(mNeedY_abscissMasg) {
//
yMsgLength = mAbscissaPaint.measureText(mYaxismax, 0, mYaxismax.length());
yMsgLength = bounds.width()<yMsgLength ? bounds.width() : yMsgLength;
yMsgLength += 5;
}
if(mSelectedMode == SELECETD_MSG_SHOW_TOP) {
//
// yMsgHeight = mSelectedTextPaint.getTextSize()+3f*mBgTriangleHeight;
yMsgHeight = CalloutHelper.getCalloutHeight();
}else {
yMsgHeight = bounds.height();
}
mChartArea = new RectF(yMsgLength+getPaddingLeft(), getPaddingTop()+yMsgHeight, mWidth+getPaddingLeft(),
getPaddingTop()+mHeight-2*mAbscissaMsgSize);
refreshChartSetData();
}
/**
*
*/
protected void refreshChartSetData(){
if(mGraphStyle == BAR) {
//
mInterval = mInterval>=MathHelper.dip2px(mContext, 6) ? MathHelper.dip2px(mContext, 6) : mInterval;
// mFixBarWidth = false;
}else {
//
mBarWidth = 3;
}
if(mScrollAble) {
mVisibleNums = mVisibleNums<=0 ? 5 : mVisibleNums;// 5
}else {
//
mVisibleNums = mVisibleNums>=mJcharts.size() ? mVisibleNums : mJcharts.size();
}
//
mCharAreaWidth = mChartArea.right-mChartArea.left;
// mVisibleNums
if(mGraphStyle == BAR) {
// minterval
mBarWidth = ( mCharAreaWidth-mInterval*( mVisibleNums-1 ) )/mVisibleNums;
}else {
mInterval = ( mCharAreaWidth-mBarWidth*mVisibleNums )/( mVisibleNums-1 );
}
refreshExcels();
}
/**
*
*/
protected void refreshExcels(){
if(mJcharts == null) {
if(BuildConfig.DEBUG) {
Log.e(TAG, " ");
}
return;
}
findTheBestChart();
mHeightRatio = ( mChartArea.bottom-mChartArea.top )/( mYaxis_Max-mYaxis_min );
for(int i = 0; i<mJcharts.size(); i++) {
Jchart jchart = mJcharts.get(i);
jchart.setLowStart(mYaxis_min);
jchart.setHeightRatio(mHeightRatio);
jchart.setWidth(mBarWidth);
PointF start = jchart.getStart();
jchart.setIndex(i);
start.x = mChartArea.left+mBarWidth*i+mInterval*i;
start.y = mChartArea.bottom-mAbove;
refreshOthersWithEveryChart(i, jchart);
}
mChartRithtest_x = mJcharts.get(mJcharts.size()-1).getMidPointF().x;
mChartLeftest_x = mJcharts.get(0).getMidPointF().x;
}
/**
* chart
*
* @param i
* @param jchart
*/
protected void refreshOthersWithEveryChart(int i, Jchart jchart){
}
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
if(null != mJcharts && mJcharts.size()>0) {
if(mNeedY_abscissMasg && mYaxis_msg != null) {
drawYabscissaMsg(canvas);
}
if(mGraphStyle == BAR) {
drawSugExcel_BAR(canvas);
}else if(mGraphStyle == LINE) {
drawSugExcel_LINE(canvas);
}else {
drawSugExcel_BAR(canvas);
drawSugExcel_LINE(canvas);
}
//
if(mSelectedMode == SELECETD_MSG_SHOW_TOP && !mValueAnimator.isRunning()) {
if(mSelected>-1) {
drawSelectedText(canvas, mJcharts.get(mSelected));
}else {
drawSelectedText(canvas, mJcharts.get(mHeightestChart.getIndex()));
}
}
for(Jchart excel : mJcharts) {
drawAbscissaMsg(canvas, excel);
}
}
drawCoordinateAxes(canvas);
mPhase = ++mPhase%50;
}
@Override
public boolean onTouchEvent(MotionEvent event){
if(mSelectedMode == -1 && !mScrollAble) {
return false;
}
return mGestureDetector.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent e){
mScroller.forceFinished(true);
return true;
}
@Override
public void onShowPress(MotionEvent e){
if(BuildConfig.DEBUG) {
Log.d(TAG, "onShowPress ");
}
}
@Override
public boolean onSingleTapUp(MotionEvent e){
PointF tup = new PointF(e.getX(), e.getY());
mSelected = clickWhere(tup);
if(mListener != null) {
mListener.onItemClick(mSelected);
}
if(BuildConfig.DEBUG) {
Log.d(TAG, "selected "+mSelected);
}
invalidate();
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY){
return judgeSliding(-distanceX);
}
@Override
public void onLongPress(MotionEvent e){
PointF tup = new PointF(e.getX(), e.getY());
mSelected = clickWhere(tup);
if(mListener != null) {
mListener.onItemLongClick(mSelected);
}
if(BuildConfig.DEBUG) {
Log.d(TAG, "onLongPress selected "+mSelected);
}
invalidate();
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY){
upPlace = e2.getX();
mScroller
.fling((int)e2.getX(), (int)e2.getY(), (int)velocityX/2, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
return true;
}
@Override
public void computeScroll(){
if(mScroller.computeScrollOffset()) {
float vSliding = mScroller.getCurrX()-upPlace;
judgeSliding(vSliding);
}
}
protected boolean judgeSliding(float tempSlided){
mSliding += tempSlided;
if(mJcharts != null && mJcharts.size()>0) {
if(mSliding>=0 || mSliding<=-( mChartRithtest_x-mCharAreaWidth )) {
//
mSliding = mSliding>=0 ? 0 : mSliding<=-( mChartRithtest_x-mCharAreaWidth ) ? -( mChartRithtest_x-mCharAreaWidth ) : mSliding;
invalidate();
return false;
}else {
//
invalidate();
return true;
}
}else {
mSliding = mSliding>=0 ? 0 : mSliding;
invalidate();
return false;
}
}
/**
*
*/
protected int clickWhere(PointF tup){
if(mChartArea == null) {
return -1;
}
float clickEffective_x = tup.x-mChartArea.left-mSliding;
if(clickEffective_x>0) {
clickEffective_x = tup.x-mChartArea.left-mBarWidth-mInterval/2-mSliding;
if(clickEffective_x>0) {
int maybeSelected = (int)( clickEffective_x/( mBarWidth+mInterval ) )+1;
if(maybeSelected>=mJcharts.size()) {
return -1;
}
//y
Jchart jchart = mJcharts.get(maybeSelected);
if(tup.y>jchart.getMidPointF().y-mAllowError) {
return maybeSelected;
}else {
return -1;
}
}else {
// y
Jchart jchart = mJcharts.get(0);
if(tup.y>jchart.getMidPointF().y-mAllowError) {
return 0;
}else {
return -1;
}
}
}else {
return -1;
}
}
/**
*
*
* @param canvas
* @param excel
*/
protected void drawSelectedText(Canvas canvas, Jchart excel){
PointF midPointF = excel.getMidPointF();
// String msg = excel.getUpper() + excel.getUnit();
String msg = excel.getShowMsg();
Rect mBounds = new Rect();
mSelectedTextPaint.getTextBounds(msg, 0, msg.length(), mBounds);
Path textBg = new Path();
// mSelectedTextPaint.getTextSize() > mBounds.height()
float bgWidth = MathHelper.dip2px(mContext, 8);
textBg.moveTo(midPointF.x, midPointF.y-mSelectedTextMarging);
textBg.lineTo(midPointF.x-bgWidth/2, midPointF.y-mSelectedTextMarging-mBgTriangleHeight-1.5f);
textBg.lineTo(midPointF.x+bgWidth/2, midPointF.y-mSelectedTextMarging-mBgTriangleHeight-1.5f);
textBg.close();
canvas.drawPath(textBg, mSelectedTextBgPaint);
RectF rectF = new RectF(midPointF.x-mBounds.width()/2f-bgWidth,
midPointF.y-mSelectedTextMarging-mBgTriangleHeight-mBounds.height()-mBgTriangleHeight*2f,
midPointF.x+mBounds.width()/2f+bgWidth, midPointF.y-mSelectedTextMarging-mBgTriangleHeight);
float dffw = 0;
if(!mScrollAble) {
//
dffw = rectF.right-mWidth-getPaddingRight()-getPaddingLeft();
}
float msgX = midPointF.x;
float magin = 1;
if(dffw>0) {
rectF.right = rectF.right-dffw-magin;
rectF.left = rectF.left-dffw-magin;
msgX = midPointF.x-dffw-magin;
}else if(rectF.left<0) {
rectF.right = rectF.right-rectF.left+magin;
msgX = midPointF.x-rectF.left+magin;
rectF.left = magin;
}
canvas.drawRoundRect(rectF, 3, 3, mSelectedTextBgPaint);
canvas.drawText(msg, msgX, midPointF.y-mSelectedTextMarging-mBgTriangleHeight*2, mSelectedTextPaint);
}
/**
*
*
* @param canvas
*/
protected void drawSugExcel_BAR(Canvas canvas){
}
/**
*
*
* @param canvas
*/
protected void drawYabscissaMsg(Canvas canvas){
mAbscissaPaint.setTextAlign(Paint.Align.LEFT);
float diffCoordinate = mChartArea.height()/( mYaxis_msg.size()-1 );
for(int i = 0; i<mYaxis_msg.size(); i++) {
float levelCoordinate = mChartArea.bottom-diffCoordinate*i;
canvas.drawText(mYaxis_msg.get(i), getPaddingLeft(), levelCoordinate, mAbscissaPaint);
if(i>0) {
Path dashPath = new Path();
dashPath.moveTo(mChartArea.left, levelCoordinate);
float ydash_x = 0;
if(mJcharts != null && mJcharts.size()>0) {
ydash_x = mChartRithtest_x<mChartArea.right ? mChartArea.right : mChartRithtest_x;
}else {
ydash_x = mChartArea.right;
}
dashPath.lineTo(ydash_x, levelCoordinate);
mAbscisDashPaint.setPathEffect(pathDashEffect(new float[]{4, 4}));
canvas.drawPath(dashPath, mAbscisDashPaint);
}
}
}
/**
*
*
* @param canvas
* @param excel
*/
protected void drawAbscissaMsg(Canvas canvas, Jchart excel){
if(mXinterval != 0 && mXNums != 0) {
drawAbscissaMsg(canvas);
}else {
mAbscissaPaint.setTextAlign(Paint.Align.CENTER);
float mWidth = this.mWidth+getPaddingLeft()+getPaddingRight();
if(null != excel) {
PointF midPointF = excel.getMidPointF();
if(!TextUtils.isEmpty(excel.getXmsg())) {
String xmsg = excel.getXmsg();
float w = mAbscissaPaint.measureText(xmsg, 0, xmsg.length());
if(!mScrollAble) {
if(midPointF.x-w/2<0) {
//
canvas.drawText(excel.getXmsg(), w/2,
mChartArea.bottom+MathHelper.dip2px(mContext, 3)+mAbscissaMsgSize, mAbscissaPaint);
}else if(midPointF.x+w/2>mWidth) {
//
canvas.drawText(excel.getXmsg(), mWidth-w/2,
mChartArea.bottom+MathHelper.dip2px(mContext, 3)+mAbscissaMsgSize, mAbscissaPaint);
}else {
canvas.drawText(excel.getXmsg(), midPointF.x,
mChartArea.bottom+MathHelper.dip2px(mContext, 3)+mAbscissaMsgSize, mAbscissaPaint);
}
}else {
canvas.drawText(excel.getXmsg(), midPointF.x,
mChartArea.bottom+MathHelper.dip2px(mContext, 3)+mAbscissaMsgSize, mAbscissaPaint);
}
}
}
}
}
private void drawAbscissaMsg(Canvas canvas){
int mTotalTime = mXinterval*mXNums;
String total = String.valueOf(mTotalTime);
float xWi = mWidth-mChartArea.left-getPaddingRight()-mAbscissaPaint.measureText(total, 0, total.length());
for(int i = 0; i<mXNums+1; i++) {
String xmsg = String.valueOf(mXinterval*i);
float w = mAbscissaPaint.measureText(xmsg, 0, xmsg.length());
float textX = mChartArea.left+mXinterval*i/mTotalTime*xWi;
if(textX+w/2>mWidth) {
textX = mWidth-w;
}
canvas.drawText(xmsg, textX, mChartArea.bottom+MathHelper.sp2px(mContext, 3)+mAbscissaMsgSize,
mAbscissaPaint);
}
}
/**
*
*/
protected void drawSugExcel_LINE(Canvas canvas){
}
/**
*
*/
protected void drawCoordinateAxes(Canvas canvas){
if(mScrollAble) {
float coordinate_x = mChartRithtest_x+mBarWidth/2;
coordinate_x = coordinate_x<mChartArea.right ? mChartArea.right : coordinate_x;
canvas.drawLine(mChartArea.left, mChartArea.bottom, coordinate_x, mChartArea.bottom, mCoordinatePaint);
}else {
canvas.drawLine(mChartArea.left, mChartArea.bottom, mChartArea.right, mChartArea.bottom, mCoordinatePaint);
}
}
/**
*
*
* @param paint
*/
protected void paintSetShader(Paint paint, int[] shaders, float x0, float y0, float x1, float y1){
if(shaders != null && shaders.length>1) {
float[] position = new float[shaders.length];
float v = 1f/shaders.length;
float temp = 0;
if(shaders.length>2) {
for(int i = 0; i<shaders.length; i++) {
position[i] = temp;
temp += v;
}
}else {
position[0] = 0;
position[1] = 1;
}
paint.setShader(new LinearGradient(x0, y0, x1, y1, shaders, position, Shader.TileMode.CLAMP));
}else if(paint.getShader() != null) {
paint.setShader(null);
}
}
protected DashPathEffect pathDashEffect(float[] intervals){ //
DashPathEffect dashEffect = new DashPathEffect(intervals, mPhase);
return dashEffect;
}
public void aniShowChar(float start, float end){
aniShowChar(start, end, mInterpolator, ANIDURATION);
}
public void aniShowChar(float start, float end, TimeInterpolator interpolator){
aniShowChar(start, end, interpolator, 1000);
}
public void aniShowChar(float start, float end, TimeInterpolator interpolator, long duration){
aniShowChar(start, end, interpolator, duration, false);
}
public void aniShowChar(float start, float end, TimeInterpolator interpolator, long duration, boolean intvalue){
mValueAnimator.cancel();
if(intvalue) {
mValueAnimator = ValueAnimator.ofInt(( (int)start ), ( (int)end ));
}else {
mValueAnimator = ValueAnimator.ofFloat(start, end);
}
mValueAnimator.setDuration(duration);
mValueAnimator.setInterpolator(interpolator);
mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation){
onAnimationUpdating(animation);
}
});
mValueAnimator.start();
}
protected void onAnimationUpdating(ValueAnimator animation){
}
/**
*
*/
public void feedData(@NonNull Jchart... jcharts){
feedData(new ArrayList<Jchart>(Arrays.asList(jcharts)));
}
/**
*
*/
public void feedData(@NonNull List<Jchart> jchartList){
mSelected = -1;
mJcharts.clear();
if(jchartList.size()>0) {
mJcharts.addAll(jchartList);
mAllLastPoints = new ArrayList<>(jchartList.size());
for(int i = 0; i<mJcharts.size(); i++) {
Jchart jchart = mJcharts.get(i);
jchart.setIndex(i);
mAllLastPoints.add(new PointF(jchart.getMidX(), -1));
}
if(mWidth>0) {
//
refreshChartSetData();
}
}else {
if(BuildConfig.DEBUG) {//in lib DEBUG always false
Log.e(TAG, " ");
}
}
}
protected void findTheBestChart(){
mFirstJchart = mJcharts.get(0);
mLastJchart = mJcharts.get(mJcharts.size()-1);
mHeightestChart = Collections.max(mJcharts, new Comparator<Jchart>() {
@Override
public int compare(Jchart lhs, Jchart rhs){
return (int)( lhs.getTopest()-rhs.getTopest() );
}
});
mMinestChart = Collections.min(mJcharts, new Comparator<Jchart>() {
@Override
public int compare(Jchart lhs, Jchart rhs){
return (int)( lhs.getTopest()-rhs.getTopest() );
}
});
if(BuildConfig.DEBUG) {
Log.d(TAG, ""+mHeightestChart.getTopest());
}
if(mYaxis_msg == null || mYaxis_msg.size() == 0) {
mYaxis_Max = MathHelper.getCeil10(mHeightestChart.getTopest());
// y
refreshYaxisValues(3);
}else {
if(mYaxis_Max<mHeightestChart.getTopest() || mYaxis_min>mMinestChart.getTopest()) {
//
mYaxis_Max = mYaxis_Max<mHeightestChart.getTopest() ? MathHelper
.getCeil10(mHeightestChart.getTopest()) : mYaxis_Max;
if(mYaxis_min>mMinestChart.getTopest()) {
mYaxis_min = MathHelper.getCast10(mMinestChart.getTopest());
}
//
refreshYaxisValues(mYaxis_msg.size());
}
}
}
public void setOnGraphItemListener(OnGraphItemListener listener){
mListener = listener;
}
public void setInterpolator(TimeInterpolator interpolator){
mInterpolator = interpolator;
}
public int getNormalColor(){
return mNormalColor;
}
/**
*
*/
public void setNormalColor(int normalColor){
mNormalColor = normalColor;
}
public int getActivationColor(){
return mActivationColor;
}
/**
*
*/
public void setActivationColor(int activationColor){
mActivationColor = activationColor;
}
public int getGraphStyle(){
return mGraphStyle;
}
public void setNeedY_abscissMasg(boolean needY_abscissMasg){
mNeedY_abscissMasg = needY_abscissMasg;
}
/**
* y
* <p>0 showYnum0y0
*
* @param min
* y
* @param max
* y
* @param showYnum
* y
*/
public void setYaxisValues(int min, int max, int showYnum){
mYaxis_Max = max;
mYaxismax = new DecimalFormat("##.#").format(mYaxis_Max);
mYaxis_min = min;
mYaxis_msg = mYaxis_msg == null ? new ArrayList<String>(showYnum) : mYaxis_msg;
refreshExcels();
}
private void refreshYaxisValues(int showYnum){
mYaxis_msg = new ArrayList<>(showYnum);
mYaxismax = new DecimalFormat("##.#").format(mYaxis_Max);
float diffLevel = ( mYaxis_Max-mYaxis_min )/( (float)showYnum-1 );
for(int i = 0; i<showYnum; i++) {
mYaxis_msg.add(new DecimalFormat("#").format(mYaxis_min+diffLevel*i));
}
}
/**
* y
*
* @param showMsg
* y
*/
public void setYaxisValues(@NonNull List<String> showMsg){
mYaxis_msg = new ArrayList<>(showMsg.size());
mYaxismax = showMsg.get(0);
for(int i = 0; i<showMsg.size(); i++) {
if(mYaxismax.length()<showMsg.get(i).length()) {
mYaxismax = showMsg.get(i);
}
mYaxis_msg.add(showMsg.get(i));
}
}
/**
* @param xNums
*
* @param xinterval
*
*/
public void setXnums(int xNums, int xinterval){
mXNums = xNums;
mXinterval = xinterval;
}
/**
* y
*
* @param showMsg
* y
*/
public void setYaxisValues(@NonNull String... showMsg){
setYaxisValues(Arrays.asList(showMsg));
}
/**
* y 0
*
* @param max
* y
* @param showYnum
* y
*/
public void setYaxisValues(int max, int showYnum){
setYaxisValues(0, max, showYnum);
}
@Override
protected void onDetachedFromWindow(){
super.onDetachedFromWindow();
if(mValueAnimator.isRunning()) {
mValueAnimator.cancel();
}
mChartArea = null;
mAllLastPoints.clear();
mAllPoints.clear();
mJcharts.clear();
}
/**
*
*
* @param abscissaMsgSize
*/
public void setAbscissaMsgSize(int abscissaMsgSize){
mAbscissaMsgSize = abscissaMsgSize;
}
/**
* +
*/
public void setGraphStyle(@GraphStyle int graphStyle){
mGraphStyle = graphStyle;
if(mWidth>0) {
refreshChartSetData();
}
}
/**
*
*
* @param sliding
*/
public void setSliding(float sliding){
mSliding = sliding;
}
/**
*
*
* @param above
*/
public void setAbove(int above){
mAbove = above;
refreshExcels();
}
public boolean isScrollAble(){
return mScrollAble;
}
/**
* {@link #setVisibleNums(int)}
*
* @param scrollAble
*/
public void setScrollAble(boolean scrollAble){
mScrollAble = scrollAble;
mSliding = 0;//0
if(mWidth>0) {
refreshChartSetData();
}
}
public float getInterval(){
return mInterval;
}
public void setInterval(float interval){
mInterval = interval;
}
public int getSelected(){
return mSelected;
}
/**
*
*
* @param selected
*/
public void setSelected(int selected){
mSelected = selected;
}
public int getVisibleNums(){
return mVisibleNums;
}
public void setSelectedTextSize(float textSize){
mSelectedTextPaint.setTextSize(textSize);
}
/**
*
* 5
*
* @param visibleNums
*/
public void setVisibleNums(int visibleNums){
mVisibleNums = visibleNums;
if(mWidth>0) {
refreshChartSetData();
}
}
public void setSelectedMode(@SelectedMode int selectedMode){
mSelectedMode = selectedMode;
}
public void aniChangeData(List<Jchart> jchartList){
}
public Paint getPaintAbsicssa(){
return mAbscissaPaint;
}
public Paint getPaintCoordinate(){
return mCoordinatePaint;
}
public Paint getPaintAbscisDash(){
return mAbscisDashPaint;
}
public Paint getSelectedTextBg(){
return mSelectedTextBgPaint;
}
public Paint getSelectedTextPaint(){
return mSelectedTextPaint;
}
}
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/inter/BaseGraph.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 7,930 |
```java
package com.jonas.jgraph.graph;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import com.jonas.jgraph.inter.BaseGraph;
import com.jonas.jgraph.models.Jchart;
import com.jonas.jgraph.utils.MathHelper;
import java.util.List;
/**
* @author yun.
* @date 2016/6/8
* @des []
* @since [path_to_url
* <p><a href="path_to_url">github</a>
*/
public class LineChar extends BaseGraph {
private boolean moved;
private float mDownX;
private boolean lineFirstMoved;
private float mBarWidth = -1;
/**
*
*/
private Jchart mHeightestExcel;
/**
* x
*/
private RectF mChartArea;
private Paint mLinePaint;
private float mLineWidth = 23;
private int mLineColor = Color.RED;
/**
*
*/
private int mAbscissaMsgSize;
/**
*
*/
private int mAbscissaMsgColor = Color.parseColor("#556A73");
/**
*
*/
private Paint mAbscissaPaint;
private float mYaxis_Max = 100;
private float mYaxis_min;
private int mYaxis_showYnum;
private float mHeightRatio;
/**
*
*/
private int mAbove;
private boolean allowInterval_left_right = true;
/**
*
*/
private int[] mShaderColors;
private Paint mAbscisDashPaint;
/**
*
*/
private float aniRatio = 1;
private Path mLinePath = new Path();
/**
*
*/
private boolean mFixBarWidth;
/**
*
*/
private float mAniRotateRatio = 0;
private float mChartRithtest_x;
/**
*
*/
private float mCharAreaWidth;
private boolean mNeedY_abscissMasg;
public LineChar(Context context) {
super(context);
}
public LineChar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LineChar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void init(Context context) {
super.init(context);
mGraphStyle = LINE;
mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mAbscissaPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mAbscisDashPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
initializeData();
}
private void initializeData() {
mBarWidth = MathHelper.dip2px(mContext,16);//
mInterval = MathHelper.dip2px(mContext,4);//
mAbscissaMsgSize = MathHelper.sp2px(mContext,12);//
mAbscissaMsgColor = Color.parseColor("#556A73");
mLineColor = Color.RED;
mLineWidth = MathHelper.dip2px(mContext,3);
mLinePaint.setStyle(Paint.Style.STROKE);
mLinePaint.setColor(mLineColor);
mLinePaint.setStrokeWidth(mLineWidth);
mAbscissaPaint.setTextAlign(Paint.Align.CENTER);
mAbscissaPaint.setTextSize(mAbscissaMsgSize);
mAbscissaPaint.setColor(mAbscissaMsgColor);
mAbscisDashPaint.setStrokeWidth(1);
mAbscisDashPaint.setStyle(Paint.Style.STROKE);
mAbscisDashPaint.setColor(mAbscissaMsgColor);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
refreshChartArea();
refreshChartSetData();
// refreshExcels();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.rotate(mAniRotateRatio);
canvas.translate(mSliding, 0);//0 0
// mLinePaint.setStrokeWidth(1);
// canvas.drawRect(mChartArea, mLinePaint);
super.onDraw(canvas);
if (mNeedY_abscissMasg) {
drawYabscissaMsg(canvas);
}
}
@Override
protected void drawSugExcel_LINE(Canvas canvas) {
//0
lineWithEvetyPoint(canvas);
//0
// lineSkip0Point(canvas);
}
/**
*
*
* @param paint
*/
private void paintSetShader(Paint paint) {
if (mShaderColors != null && mShaderColors.length > 1) {
float[] position = new float[mShaderColors.length];
float v = 1f / mShaderColors.length;
float temp = 0;
for (int i = 0; i < mShaderColors.length; i++) {
position[i] = temp;
temp += v;
}
paint.setShader(new LinearGradient(mChartArea.left, mChartArea.top, mChartArea.left, mChartArea.bottom
, mShaderColors, position, Shader.TileMode.CLAMP));
}
}
private void lineWithEvetyPoint(Canvas canvas) {
paintSetShader(mLinePaint);
// Path mPath = new Path();
// mPath.moveTo(50, 150);
// mPath.cubicTo(125, 150, 125, 50, 200, 50);
// canvas.drawPath(mPath, mLinePaint);
if (mShaderColors != null && mShaderColors.length > 1) {
float[] position = new float[mShaderColors.length];
float v = 1f / mShaderColors.length;
float temp = 0;
for (int i = 0; i < mShaderColors.length; i++) {
position[i] = temp;
temp += v;
}
mLinePaint.setShader(new LinearGradient(mChartArea.left, mChartArea.top, mChartArea.left, mChartArea.bottom
, mShaderColors, position, Shader.TileMode.CLAMP));
}
canvas.drawPath(mLinePath, mLinePaint);
// mLinePath.reset();
for (int i = 0; i < mJcharts.size(); i++) {
Jchart jchart = mJcharts.get(i);
// if (i<mJcharts.size()-1) {
// PointF startPoint = mJcharts.get(i).getMidPointF();
// PointF endPoint = mJcharts.get(i + 1).getMidPointF();
// if (i == 0) mLinePath.moveTo(startPoint.x, startPoint.y);
// float controllA_X = (startPoint.x + endPoint.x) /2;
// float controllA_Y = startPoint.y;
// float controllB_X = (startPoint.x + endPoint.x) /2;
// float controllB_Y = endPoint.y;
// mLinePath.cubicTo(controllA_X, controllA_Y, controllB_X, controllB_Y, endPoint.x, endPoint.y);
// canvas.drawCircle(controllA_X,controllA_Y,2,mLinePaint);
// canvas.drawCircle(controllB_X,controllB_Y,2,mLinePaint);
// canvas.drawCircle(startPoint.x,startPoint.y,2,mLinePaint);
// canvas.drawLine(startPoint.x,startPoint.y,controllA_X,controllA_Y,mLinePaint);
// canvas.drawLine(endPoint.x,endPoint.y,controllB_X,controllB_Y,mLinePaint);
// }
drawAbscissaMsg(canvas, jchart);
}
}
private void lineSkip0Point(Canvas canvas) {
mLinePath.reset();
for (int i = 0; i < mJcharts.size(); i++) {
Jchart jchart = mJcharts.get(i);
PointF midPointF = jchart.getMidPointF();
if (i == 0) {
mLinePath.moveTo(midPointF.x, midPointF.y);
} else {
mLinePath.lineTo(midPointF.x, midPointF.y);
}
drawAbscissaMsg(canvas, jchart);
}
}
protected void drawCoordinateAxes(Canvas canvas) {
if (mJcharts != null && mJcharts.size() > 0) {
canvas.drawLine(mChartArea.left, mChartArea.bottom, mJcharts.get(mJcharts.size() - 1).getMidPointF().x, mChartArea.bottom, mCoordinatePaint);
} else {
canvas.drawLine(mChartArea.left, mChartArea.bottom, mChartArea.right, mChartArea.bottom, mCoordinatePaint);
}
}
@Override
public void setGraphStyle(int graphStyle) {
mGraphStyle = LINE;
}
/**
*
*/
public void feedData(List<Jchart> jchartList) {
lineFirstMoved = false;
mSelected = -1;
mJcharts.clear();
if (jchartList != null && jchartList.size() > 0) {
mHeightestExcel = jchartList.get(0);
for (Jchart jchart : jchartList) {
mHeightestExcel = mHeightestExcel.getHeight() > jchart.getHeight() ? mHeightestExcel : jchart;
}
for (int i = 0; i < jchartList.size(); i++) {
Jchart jchart = jchartList.get(i);
jchart.setWidth(mBarWidth);
PointF start = jchart.getStart();
start.x = mInterval * (i + 1) + mBarWidth * i;
mJcharts.add(jchart);
}
if (mWidth > 0) {
//
refreshChartSetData();
}
}
postInvalidate();
}
/**
*
*/
protected void refreshExcels() {
if (mYaxis_Max <= 0) {
mYaxis_Max = mHeightestExcel.getHeight();
}
// mHeightRatio = (mChartArea.bottom - mChartArea.top) / (mHeightestExcel.getHeight() - mYaxis_min);
mHeightRatio = (mChartArea.bottom - mChartArea.top) / (mYaxis_Max - mYaxis_min);
for (int i = 0; i < mJcharts.size(); i++) {
Jchart jchart = mJcharts.get(i);
jchart.setHeight(( jchart.getHeight() - mYaxis_min) * mHeightRatio);//
jchart.setWidth(mBarWidth);
PointF start = jchart.getStart();
//
start.x = mChartArea.left + mBarWidth * i + mInterval * i;
start.y = mChartArea.bottom - mAbove - jchart.getLower();
jchart.setColor(mNormalColor);
}
// path
mLinePath.reset();
for (int i = 0; i < mJcharts.size(); i++) {
Jchart jchart = mJcharts.get(i);
if (i < mJcharts.size() - 1) {
PointF startPoint = jchart.getMidPointF();
PointF endPoint = mJcharts.get(i + 1).getMidPointF();//
if (i == 0) mLinePath.moveTo(startPoint.x, startPoint.y);
float controllA_X = (startPoint.x + endPoint.x) / 2;
float controllA_Y = startPoint.y;
float controllB_X = (startPoint.x + endPoint.x) / 2;
float controllB_Y = endPoint.y;
mLinePath.cubicTo(controllA_X, controllA_Y, controllB_X, controllB_Y, endPoint.x, endPoint.y);
}
}
mChartRithtest_x = mJcharts.get(mJcharts.size() - 1).getMidPointF().x;
}
@Override
public void setInterval(float interval) {
super.setInterval(interval);
refreshChartSetData();
}
/**
* y
*
* @param min y
* @param max y
* @param showYnum y
*/
public void setYaxisValues(int min, int max, int showYnum) {
mYaxis_Max = max;
mYaxis_min = min;
mYaxis_showYnum = showYnum;
}
/**
* y 0
*
* @param max y
* @param showYnum y
*/
public void setYaxisValues(int max, int showYnum) {
setYaxisValues(0, max, showYnum);
}
/**
*
*
* @param abscissaMsgColor
*/
public void setAbscissaMsgColor(int abscissaMsgColor) {
mAbscissaMsgColor = abscissaMsgColor;
}
/**
*
*
* @param abscissaMsgSize
*/
public void setAbscissaMsgSize(int abscissaMsgSize) {
mAbscissaMsgSize = abscissaMsgSize;
}
/**
*
*
* @param lineColor
*/
public void setLineColor(int lineColor) {
mLineColor = lineColor;
}
/**
*
*
* @param lineWidth
*/
public void setLineWidth(float lineWidth) {
mLineWidth = lineWidth;
}
/**
*
*
*
* @param colors
*/
public void setShaderColors(int... colors) {
mShaderColors = colors;
}
/**
* y
*
* @param yaxis_min
*/
public void setYaxis_min(float yaxis_min) {
mYaxis_min = yaxis_min;
}
/**
* y
*
* @param yaxis_showYnum
*/
public void setYaxis_showYnum(int yaxis_showYnum) {
mYaxis_showYnum = yaxis_showYnum;
}
/**
* y
*
* @param yaxis_Max
*/
public void setYaxis_Max(float yaxis_Max) {
mYaxis_Max = yaxis_Max;
}
/**
*
*
* @param allowInterval_left_right
*/
public void setAllowInterval_left_right(boolean allowInterval_left_right) {
this.allowInterval_left_right = allowInterval_left_right;
}
/**
*
*
* @param above
*/
public void setAbove(int above) {
mAbove = above;
}
}
// barwidth
//
//
// 1 mVisibleNums
// 2 mVisibleNums mExecels
//
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/graph/LineChar.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 3,227 |
```java
package com.jonas.jgraph.graph;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import com.jonas.jgraph.models.Jchart;
import com.jonas.jgraph.inter.BaseGraph;
import com.jonas.jgraph.utils.MathHelper;
import java.util.List;
/**
* @author yun.
* @date 2015/9/2
* @des []
* @since [path_to_url
* <p><a href="path_to_url">github</a>
*/
public class PieGraph extends BaseGraph {
private static final int PIE = 4;
private float dataFloatTotal;
private Paint mPiePaint;
private float pieWidth = 20;
/**
*
*/
private float mSquare;
/**
*
*/
private RectF mAecRect;
/**
*
*/
private float mOutPading = 1;
private float mStartAnger;
private Paint mIntervalPaint;
private int mIntervalColor;
/**
*
*/
private float mArcRadio;
private float mIntervalWidth;
public PieGraph(Context context) {
super(context);
}
public PieGraph(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PieGraph(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mSquare = mWidth > mHeight ? mHeight : mWidth;
refreshPieSet();
}
@Override
protected void init(Context context) {
super.init(context);
mGraphStyle = PIE;
mPiePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPiePaint.setStyle(Paint.Style.STROKE);
mIntervalPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
initData();
}
/**
*
*/
protected void initData() {
mInterval = 10;
mPiePaint.setStrokeWidth(pieWidth);
mAecRect = new RectF(0, 0, mWidth, mHeight);
mIntervalPaint.setStrokeWidth(MathHelper.dip2px(mContext,1));
Drawable background = getBackground();
if (background instanceof ColorDrawable) {
mIntervalColor = ((ColorDrawable) background).getColor();
} else {
mIntervalColor = Color.WHITE;
}
}
@Override
protected void onDraw(Canvas canvas) {
if (mJcharts != null && mJcharts.size() > 0) {
drawSugExcel_PIE(canvas);
}
}
protected void drawSugExcel_PIE(Canvas canvas) {
mStartAnger = 0;
for (Jchart excel : mJcharts) {
mPiePaint.setColor(excel.getColor());
canvas.drawArc(mAecRect, mStartAnger, excel.getPercent(), false, mPiePaint);
mStartAnger += excel.getPercent();
}
mIntervalPaint.setStrokeWidth(mIntervalWidth);
mIntervalPaint.setColor(mIntervalColor);
canvas.save();
for (Jchart excel : mJcharts) {
canvas.drawLine(mCenterPoint.x + mArcRadio - pieWidth / 2 - 0.25f, mCenterPoint.y, mCenterPoint.x + mArcRadio - pieWidth / 2 + pieWidth, mCenterPoint.y, mIntervalPaint);
canvas.rotate(excel.getPercent(), mCenterPoint.x, mCenterPoint.y);
}
canvas.restore();
}
@Override
public void feedData(List<Jchart> jchartList) {
mJcharts.clear();
//sugexcellower0 upper height
for (Jchart jchart : jchartList) {
dataFloatTotal += jchart.getUpper();
}
mJcharts.addAll(jchartList);
//
for (Jchart excel : mJcharts) {
excel.setPercent(excel.getUpper() / dataFloatTotal * 360);
}
refreshPieSet();
}
/**
*
*/
private void refreshPieSet() {
if (mHeight > 0) {
//
pieWidth = pieWidth > (mSquare / 2 - mOutPading) ? (mSquare / 2 - mOutPading) : pieWidth;
mPiePaint.setStrokeWidth(pieWidth);
mIntervalWidth = mIntervalWidth < pieWidth / 10f ? pieWidth / 10f : mIntervalWidth;
mArcRadio = mSquare / 2 - mOutPading - pieWidth / 2;
mAecRect.set(mCenterPoint.x - mArcRadio, mCenterPoint.y - mArcRadio, mCenterPoint.x + mArcRadio, mCenterPoint.y + mArcRadio);
postInvalidate();
}
}
public float getPieWidth() {
return pieWidth;
}
public void setPieWidth(float pieWidth) {
this.pieWidth = pieWidth;
refreshPieSet();
}
@Override
public void setInterval(float interval) {
super.setInterval(interval);
mIntervalWidth = interval;
refreshPieSet();
}
}
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/graph/PieGraph.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 1,162 |
```java
package com.jonas.jgraph.graph;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.PointF;
import android.graphics.RectF;
import android.support.annotation.ColorInt;
import android.support.annotation.DimenRes;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.Log;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;
import com.jonas.jgraph.BuildConfig;
import com.jonas.jgraph.R;
import com.jonas.jgraph.inter.BaseGraph;
import com.jonas.jgraph.models.Jchart;
import com.jonas.jgraph.utils.CalloutHelper;
import com.jonas.jgraph.utils.DrawHelper;
import com.jonas.jgraph.utils.MathHelper;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
/**
* @author yun.
* @date 2016/6/8
* @des []
* @since [path_to_url
* <p><a href="path_to_url">github</a>
*/
public class JcoolGraph extends BaseGraph {
private static final String TAG = JcoolGraph.class.getSimpleName();
private Paint mBarPaint;
private int mBarStanded = 0;
private boolean lineStarted;
private ArrayList<Path> mDashPathList = new ArrayList<>();
private ArrayList<Path> mLinePathList = new ArrayList<>();
private Paint mDashLinePaint;
private Paint mPointPaint;
private float mLinePointRadio;
/**
*
*/
public final static int LINE_BROKEN = 0;
/**
*
*/
public final static int LINE_CURVE = 1;
@Retention(RetentionPolicy.SOURCE)
@IntDef({LINE_BROKEN, LINE_CURVE})
public @interface LineStyle {
}
/**
*
*/
public final static int LINESHOW_DRAWING = 0;
/**
*
*/
public final static int LINESHOW_SECTION = 1;
/**
* /
*/
public final static int LINESHOW_FROMLINE = 2;
/**
*
*/
public final static int LINESHOW_FROMCORNER = 3;
/**
*
*/
public final static int LINESHOW_ASWAVE = 4;
@Retention(RetentionPolicy.SOURCE)
@IntDef({LINESHOW_DRAWING, LINESHOW_SECTION, LINESHOW_FROMLINE, LINESHOW_FROMCORNER, LINESHOW_ASWAVE})
public @interface LineShowStyle {}
/**
*
*/
public final static int BARSHOW_ASWAVE = 0;
/**
* /
*/
public final static int BARSHOW_FROMLINE = 1;
/**
*
*/
public final static int BARSHOW_EXPAND = 2;
/**
*
*/
public final static int BARSHOW_SECTION = 3;
@Retention(RetentionPolicy.SOURCE)
@IntDef({BARSHOW_ASWAVE, BARSHOW_FROMLINE, BARSHOW_EXPAND, BARSHOW_SECTION})
public @interface BarShowStyle {}
private int mBarShowStyle = BARSHOW_ASWAVE;
public final static int SHOWFROMTOP = 0;
public final static int SHOWFROMBUTTOM = 1;
public final static int SHOWFROMMIDDLE = 2;
@Retention(RetentionPolicy.SOURCE)
@IntDef({SHOWFROMTOP, SHOWFROMBUTTOM, SHOWFROMMIDDLE})
public @interface ShowFromMode {}
/**
*
*/
public final static int LINE_EVERYPOINT = 0;
/**
* 0
*/
public final static int LINE_JUMP0 = 1;
/**
* 0
*/
public final static int LINE_DASH_0 = 2;
@Retention(RetentionPolicy.SOURCE)
@IntDef({LINE_EVERYPOINT, LINE_JUMP0, LINE_DASH_0})
public @interface LineMode {
}
private int mLineMode = LINE_EVERYPOINT;
private int mShowFromMode = SHOWFROMMIDDLE;
private int mLineStyle = LINE_CURVE;
/**
* linepath
*/
private float[] mCurPosition = new float[2];
private PathMeasure mPathMeasure;
private PointF mPrePoint;
/**
*
*/
private float mBetween2Excel;
/**
*
*/
private Paint mShaderAreaPaint;
private int[] mShaderAreaColors;
private Path mAniShadeAreaPath = new Path();
private Path mShadeAreaPath = new Path();
/**
*
*/
protected int mLineShowStyle = LINESHOW_ASWAVE;
private Paint mLinePaint;
private float mLineWidth = -1;
/**
*
*/
private int[] mShaderColors;
/**
*
*/
private float mAniRatio = 1;
/**
*
*/
private Path mLinePath = new Path();
private Path mAniLinePath = new Path();
/**
*
*/
private float mAniRotateRatio = 0;
public JcoolGraph(Context context){
super(context);
}
public JcoolGraph(Context context, AttributeSet attrs){
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AndroidJgraph);
mLineStyle = a.getInteger(R.styleable.AndroidJgraph_linestyle, LINE_CURVE);
mLineMode = a.getInteger(R.styleable.AndroidJgraph_linemode, LINE_EVERYPOINT);
mLineWidth = a.getDimension(R.styleable.AndroidJgraph_linewidth, MathHelper.dip2px(mContext, 1.2f));
mLineShowStyle = a.getInt(R.styleable.AndroidJgraph_lineshowstyle, LINESHOW_ASWAVE);
a.recycle();
initializeData();
}
public JcoolGraph(Context context, AttributeSet attrs, int defStyleAttr){
super(context, attrs, defStyleAttr);
}
@Override
protected void init(Context context){
super.init(context);
mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPointPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mShaderAreaPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mDashLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
private void initializeData(){
mLineWidth = mLineWidth == -1 ? MathHelper.dip2px(mContext, 1.2f) : mLineWidth;
// style
mLinePaint.setStyle(Paint.Style.STROKE);
mDashLinePaint.setStyle(Paint.Style.STROKE);
mLinePaint.setColor(mNormalColor);
mDashLinePaint.setColor(mNormalColor);
mBarPaint.setColor(mNormalColor);
mLinePaint.setStrokeWidth(mLineWidth);
mDashLinePaint.setStrokeWidth(mLineWidth);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh){
super.onSizeChanged(w, h, oldw, oldh);
paintSetShader(mShaderAreaPaint, mShaderAreaColors);
paintSetShader(mLinePaint, mShaderColors);
paintSetShader(mBarPaint, mShaderColors);
}
@Override
protected void onDraw(Canvas canvas){
canvas.save();
canvas.rotate(mAniRotateRatio);
canvas.translate(mSliding, 0);
super.onDraw(canvas);
canvas.restore();
//
if(mNeedY_abscissMasg && mYaxis_msg != null) {
drawYabscissaMsg(canvas);
}
}
@Override
protected void drawSugExcel_BAR(Canvas canvas){
for(Jchart jchart : mJcharts) {
canvas.drawRect(jchart.getStandedRectF(), mCoordinatePaint);
}
if(mState == aniChange && mAniRatio<1) {
barAniChanging(canvas);
// for(Jchart jchart : mJcharts) {
// jchart.draw(canvas, mCoordinatePaint, false);
// }
}else {
mState = -1;
if(mLastJchart.getAniratio()>=1 && !mValueAnimator.isRunning()) {
for(Jchart jchart : mJcharts) {
jchart.draw(canvas, mBarPaint, false);
}
}else if(mBarShowStyle == BARSHOW_ASWAVE) {
for(Jchart jchart : mJcharts) {
jchart.draw(canvas, mBarPaint, false);
}
}else if(mBarShowStyle == BARSHOW_FROMLINE) {
barAniChanging(canvas);
}else if(mBarShowStyle == BARSHOW_EXPAND) {
drawBarExpand(canvas);
}else if(mBarShowStyle == BARSHOW_SECTION) {
drawBarSection(canvas);
}
}
}
private void drawBarSection(Canvas canvas){
for(int i = 0; i<( (int)mAniRatio ); i++) {
Jchart jchart = mJcharts.get(i);
jchart.draw(canvas, mBarPaint, false);
}
}
private void drawBarExpand(Canvas canvas){
for(Jchart jchart : mJcharts) {
if(mBarStanded>=mJcharts.size()) {
mBarStanded = mJcharts.size()-1;
}
Jchart sjchart = mJcharts.get(mBarStanded);
//mBarStanded
canvas.drawRect(sjchart.getRectF().left+( jchart.getRectF().left-sjchart.getRectF().left )*mAniRatio,
jchart.getRectF().top,
sjchart.getRectF().right+( jchart.getRectF().right-sjchart.getRectF().right )*mAniRatio,
jchart.getRectF().bottom, mBarPaint);
}
}
private void barAniChanging(Canvas canvas){
for(int i = 0; i<mJcharts.size(); i++) {
Jchart jchart = mJcharts.get(i);
float lasty = mAllLastPoints.get(i).y;
RectF rectF = jchart.getRectF();
// if(jchart.mTopRound) {
// Path rectFPath = jchart.getRectFPath(rectF.bottom, lasty+( rectF.top-lasty )*mAniRatio);
// canvas.drawPath(rectFPath,mBarPaint);
// }else {
// RectF drectf = new RectF(rectF.left, lasty+( rectF.top-lasty )*mAniRatio, rectF.right, rectF.bottom);
// canvas.drawRect(drectf, mBarPaint);
// }
RectF drectf = new RectF(rectF.left, lasty+( rectF.top-lasty )*mAniRatio, rectF.right, rectF.bottom);
canvas.drawRect(drectf, mBarPaint);
}
}
@Override
protected void drawSugExcel_LINE(Canvas canvas){
if(mState == aniChange && mAniRatio<1) {
drawLineAllFromLine(canvas);
for(Jchart jchart : mJcharts) {
jchart.draw(canvas, mLinePaint, true);
}
drawLeftShaderArea(canvas);
}else {
mState = -1;
if(mLineMode == LINE_EVERYPOINT) {
//0
lineWithEvetyPoint(canvas);
}else {
//0
lineSkip0Point(canvas);
}
// }
}
//
if(mLinePointRadio>0) {
for(Jchart jchart : mJcharts) {
if(jchart.getHeight()>0) {
PointF midPointF = jchart.getMidPointF();
canvas.drawCircle(midPointF.x, midPointF.y, mLinePointRadio, mPointPaint);
// mPointPaint.setColor(Color.parseColor("#ffffffff"));
mPointPaint.setColor(0Xffffffff);
mPointPaint.setStrokeWidth(MathHelper.dip2px(mContext, 2));
canvas.drawCircle(midPointF.x, midPointF.y, mLinePointRadio, mPointPaint);
}
}
}
}
/**
*
*
* @param paint
*/
protected void paintSetShader(Paint paint, int[] shaders){
paintSetShader(paint, shaders, mChartArea.left, mChartArea.top, mChartArea.left, mChartArea.bottom);
}
private void lineWithEvetyPoint(Canvas canvas){
if(( mLineShowStyle == LINESHOW_FROMCORNER || mLineShowStyle == LINESHOW_DRAWING ||
mLineShowStyle == LINESHOW_SECTION ) && !mValueAnimator.isRunning()) {
if(BuildConfig.DEBUG) {
Log.d(TAG, "drawSugExcel_LINE animationfinish to the initial state");
}
//
mAniShadeAreaPath.reset();
mAniLinePath.reset();
canvas.drawPath(mLinePath, mLinePaint);
if(mShaderAreaColors != null) {
canvas.drawPath(mShadeAreaPath, mShaderAreaPaint);
}
}else if(mLineShowStyle == LINESHOW_DRAWING) {
drawLineAllpointDrawing(canvas);
}else if(mLineShowStyle == LINESHOW_SECTION) {
drawLineAllpointSectionMode(canvas);
}else if(mLineShowStyle == LINESHOW_FROMLINE) {
drawLineAllFromLine(canvas);
drawLeftShaderArea(canvas);
}else if(mLineShowStyle == LINESHOW_FROMCORNER) {
drawLineAllFromCorner(canvas);
drawLeftShaderArea(canvas);
}else if(mLineShowStyle == LINESHOW_ASWAVE) {
drawLineAsWave(canvas);
drawLeftShaderArea(canvas);
}
}
private void drawLeftShaderArea(Canvas canvas){
//
if(mShaderAreaColors != null) {
mAniShadeAreaPath.lineTo(mChartRithtest_x, mChartArea.bottom);
mAniShadeAreaPath.lineTo(mChartLeftest_x, mChartArea.bottom);
mAniShadeAreaPath.close();
canvas.drawPath(mAniShadeAreaPath, mShaderAreaPaint);
}
}
private void drawLineAllFromCorner(Canvas canvas){
mAniShadeAreaPath.reset();
mAniLinePath.reset();
if(mLineStyle == LINE_CURVE) {
for(int i = 0; i<mAllPoints.size()-1; i++) {
PointF midPointF = mAllPoints.get(i);
PointF endPointF = mAllPoints.get(i+1);
if(mAniLinePath.isEmpty()) {
mAniLinePath.moveTo(midPointF.x*mAniRatio, midPointF.y*mAniRatio);
mAniShadeAreaPath.moveTo(midPointF.x*mAniRatio, midPointF.y*mAniRatio);
}
float con_x = ( midPointF.x+endPointF.x )/2;
mAniLinePath.cubicTo(con_x*mAniRatio, midPointF.y*mAniRatio, con_x*mAniRatio, endPointF.y*mAniRatio,
endPointF.x*mAniRatio, endPointF.y*mAniRatio);
mAniShadeAreaPath
.cubicTo(con_x*mAniRatio, midPointF.y*mAniRatio, con_x*mAniRatio, endPointF.y*mAniRatio,
endPointF.x*mAniRatio, endPointF.y*mAniRatio);
}
}else {
for(PointF midPointF : mAllPoints) {
if(mAniLinePath.isEmpty()) {
mAniLinePath.moveTo(midPointF.x*mAniRatio, midPointF.y*mAniRatio);
mAniShadeAreaPath.moveTo(midPointF.x*mAniRatio, midPointF.y*mAniRatio);
}else {
mAniLinePath.lineTo(midPointF.x*mAniRatio, midPointF.y*mAniRatio);
mAniShadeAreaPath.lineTo(midPointF.x*mAniRatio, midPointF.y*mAniRatio);
}
}
}
canvas.drawPath(mAniLinePath, mLinePaint);
}
private void drawLineAllFromLine(Canvas canvas){
mAniShadeAreaPath.reset();
mAniLinePath.reset();
if(BuildConfig.DEBUG) {
canvas.drawLine(0, mChartArea.bottom, mWidth, mChartArea.bottom, mLinePaint);
canvas.drawLine(0, mChartArea.top, mWidth, mChartArea.top, mLinePaint);
}
if(mAllPoints.size() != mJcharts.size()) {
throw new RuntimeException("mAllPoints.size() == mJcharts.size()");
}
if(mLineStyle == LINE_CURVE) {
for(int i = 0; i<mAllPoints.size()-1; i++) {
PointF midPointF = mAllPoints.get(i);
PointF endPointF = mAllPoints.get(i+1);
PointF midLastPointF = mAllLastPoints.get(i);
PointF endLastPointF = mAllLastPoints.get(i+1);
if(mAniLinePath.isEmpty()) {
mAniLinePath.moveTo(midPointF.x, midLastPointF.y+( midPointF.y-midLastPointF.y )*mAniRatio);
mAniShadeAreaPath.moveTo(midPointF.x, midLastPointF.y+( midPointF.y-midLastPointF.y )*mAniRatio);
}
DrawHelper.AnipathCubicFromLast(mAniLinePath, midPointF, endPointF, midLastPointF, endLastPointF,
mAniRatio);
DrawHelper.AnipathCubicFromLast(mAniShadeAreaPath, midPointF, endPointF, midLastPointF, endLastPointF,
mAniRatio);
}
}else {
for(int i = 0; i<mAllPoints.size(); i++) {
PointF midPointF = mAllPoints.get(i);
PointF lastPointF = mAllLastPoints.get(i);
if(mAniLinePath.isEmpty()) {
mAniLinePath.moveTo(midPointF.x, lastPointF.y+( midPointF.y-lastPointF.y )*mAniRatio);
mAniShadeAreaPath.moveTo(midPointF.x, lastPointF.y+( midPointF.y-lastPointF.y )*mAniRatio);
}else {
DrawHelper.AnipathLinetoFromLast(mAniLinePath, midPointF, lastPointF, mAniRatio);
DrawHelper.AnipathLinetoFromLast(mAniShadeAreaPath, midPointF, lastPointF, mAniRatio);
}
}
}
canvas.drawPath(mAniLinePath, mLinePaint);
}
private void drawLineAsWave(Canvas canvas){
mAniShadeAreaPath.reset();
mAniLinePath.reset();
if(mLineStyle == LINE_CURVE) {
setUpCurveLinePath();
}else {
setUpBrokenLinePath();
}
canvas.drawPath(mAniLinePath, mLinePaint);
}
private void setUpCurveLinePath(){
for(int i = 0; i<mJcharts.size()-1; i++) {
PointF startPoint = mJcharts.get(i).getMidPointF();
PointF endPoint = mJcharts.get(i+1).getMidPointF();//
if(mAniLinePath.isEmpty()) {
mAniLinePath.moveTo(startPoint.x, startPoint.y);
mAniShadeAreaPath.moveTo(startPoint.x, startPoint.y);
}
DrawHelper.pathCubicTo(mAniLinePath, startPoint, endPoint);
DrawHelper.pathCubicTo(mAniShadeAreaPath, startPoint, endPoint);
}
}
private void setUpBrokenLinePath(){
for(Jchart chart : mJcharts) {
if(mAniLinePath.isEmpty()) {
mAniLinePath.moveTo(chart.getMidPointF().x, chart.getMidPointF().y);
mAniShadeAreaPath.moveTo(chart.getMidPointF().x, chart.getMidPointF().y);
}else {
mAniLinePath.lineTo(chart.getMidPointF().x, chart.getMidPointF().y);
mAniShadeAreaPath.lineTo(chart.getMidPointF().x, chart.getMidPointF().y);
}
}
}
/**
*
*
* @param canvas
*/
private void drawLineAllpointDrawing(Canvas canvas){
if(mCurPosition == null) {
return;
}
//
if(mAniLinePath.isEmpty() || mCurPosition[0]<=mChartLeftest_x) {
mPrePoint = mJcharts.get(0).getMidPointF();
mAniLinePath.moveTo(mPrePoint.x, mPrePoint.y);
mAniShadeAreaPath.moveTo(mPrePoint.x, mPrePoint.y);
}else {
if(mPrePoint == null) {
mPrePoint = mJcharts.get(0).getMidPointF();
}
if(mLineStyle == LINE_CURVE) {
float con_X = ( mPrePoint.x+mCurPosition[0] )/2;
mAniLinePath.cubicTo(con_X, mPrePoint.y, con_X, mCurPosition[1], mCurPosition[0], mCurPosition[1]);
mAniShadeAreaPath.cubicTo(con_X, mPrePoint.y, con_X, mCurPosition[1], mCurPosition[0], mCurPosition[1]);
}else {
mAniLinePath.lineTo(mCurPosition[0], mCurPosition[1]);
mAniShadeAreaPath.lineTo(mCurPosition[0], mCurPosition[1]);
}
mPrePoint.x = mCurPosition[0];
mPrePoint.y = mCurPosition[1];
}
canvas.drawPath(mAniLinePath, mLinePaint);
Jchart jchart = mJcharts.get((int)( ( mCurPosition[0]-mChartArea.left )/mBetween2Excel ));
drawAbscissaMsg(canvas, jchart);
}
/**
*
*
* @param canvas
*/
private void drawLineAllpointSectionMode(Canvas canvas){
int currPosition = (int)mAniRatio;
if(currPosition == 0) {
mAniLinePath.reset();
mAniShadeAreaPath.reset();
}
Jchart jchart = mJcharts.get(currPosition);
if(mLineStyle == LINE_BROKEN) {
if(currPosition == 0) {
mAniLinePath.moveTo(jchart.getMidPointF().x, jchart.getMidPointF().y);
}else {
mAniLinePath.lineTo(jchart.getMidPointF().x, jchart.getMidPointF().y);
}
canvas.drawPath(mAniLinePath, mLinePaint);
}else {
PointF currPointf = jchart.getMidPointF();
if(mPrePoint == null) {
mPrePoint = mJcharts.get(0).getMidPointF();
}
if(currPosition == 0) {
mAniLinePath.moveTo(mPrePoint.x, mPrePoint.y);
}
DrawHelper.pathCubicTo(mAniLinePath, mPrePoint, currPointf);
mPrePoint = currPointf;
canvas.drawPath(mAniLinePath, mLinePaint);
}
drawAbscissaMsg(canvas, jchart);
//
if(mShaderAreaColors != null) {
mAniShadeAreaPath.reset();
for(int i = 0; i<currPosition+1; i++) {
PointF currPoint = mAllPoints.get(i);
if(i == 0) {
mAniShadeAreaPath.moveTo(currPoint.x, currPoint.y);
}else {
if(mLineStyle == LINE_BROKEN) {
mAniShadeAreaPath.lineTo(currPoint.x, currPoint.y);
}else {
DrawHelper.pathCubicTo(mAniShadeAreaPath, mAllPoints.get(i-1), currPoint);
}
}
}
mAniShadeAreaPath.lineTo(jchart.getMidX(), mChartArea.bottom);
mAniShadeAreaPath.lineTo(mChartLeftest_x, mChartArea.bottom);
mAniShadeAreaPath.close();
canvas.drawPath(mAniShadeAreaPath, mShaderAreaPaint);
}
}
/**
* 0
*
* @param canvas
*/
private void lineSkip0Point(Canvas canvas){
arrangeLineDate(canvas);
if(mLineMode == LINE_DASH_0) {
//
arrangeDashLineDate(canvas);
if(mDashPathList.size()>0) {
for(Path path : mDashPathList) {
mDashLinePaint.setPathEffect(pathDashEffect(new float[]{8, 5}));
canvas.drawPath(path, mDashLinePaint);
}
postInvalidateDelayed(50);
}
}
}
protected void arrangeDashLineDate(Canvas canvas){
mDashPathList.clear();
for(int i = 0; i<mLinePathList.size(); i++) {
Path path = mLinePathList.get(i);
PathMeasure pathMeasure = new PathMeasure(path, false);
float length = pathMeasure.getLength();
float[] post = new float[2];
pathMeasure.getPosTan(0, post, null);
float[] post_end = new float[2];
pathMeasure.getPosTan(length, post_end, null);
if(length>0.001f) {
if(mShaderAreaColors != null && mShaderAreaColors.length>0) {
path.lineTo(post_end[0], mChartArea.bottom);
path.lineTo(post[0], mChartArea.bottom);//
path.close();
canvas.drawPath(path, mShaderAreaPaint);
}
}else {
post_end[0] = post[0];
post_end[1] = post[1];
}
if(i<mLinePathList.size()-1) {
path = new Path();
//
path.moveTo(post_end[0], post_end[1]);
//
PathMeasure pathMeasuredotted = new PathMeasure(mLinePathList.get(i+1), false);
pathMeasuredotted.getPosTan(0, post, null);
if(mLineStyle == LINE_BROKEN) {
path.lineTo(post[0], post[1]);
}else {
DrawHelper.pathCubicTo(path, new PointF(post_end[0], post_end[1]), new PointF(post[0], post[1]));
}
mDashPathList.add(path);
}
}
}
protected boolean arrangeLineDate(Canvas canvas){
Path pathline = null;
mLinePathList.clear();
for(int i = 0; i<mJcharts.size(); i++) {
if(!lineStarted) {
pathline = new Path();
}
Jchart excel = null;
excel = mJcharts.get(i);
PointF midPointF = excel.getMidPointF();
if(pathline != null) {
if(excel.getHeight()>0) {
if(!lineStarted) {
pathline.moveTo(midPointF.x, midPointF.y);
lineStarted = true;
}else {
if(mLineStyle == LINE_BROKEN) {
if(mLineShowStyle == LINESHOW_ASWAVE) {
pathline.lineTo(midPointF.x, midPointF.y);
}else {
PointF lastP = mAllLastPoints.get(i);
DrawHelper.AnipathLinetoFromLast(pathline, midPointF, lastP, mAniRatio);
}
}else {
if(mLineShowStyle == LINESHOW_ASWAVE) {
DrawHelper.pathCubicTo(pathline, mPrePoint, midPointF);
}else {
PointF laste = mAllLastPoints.get(i);
PointF lastP = mAllLastPoints.get(i-1);
DrawHelper
.AnipathCubicFromLast(pathline, mPrePoint, midPointF, lastP, laste, mAniRatio);
}
}
}
}else {
//
if(!pathline.isEmpty()) {
PathMeasure pathMeasure = new PathMeasure(pathline, false);
if(i>0 && pathMeasure.getLength()<0.001f) {
//
pathline.lineTo(mPrePoint.x, mPrePoint.y+0.001f);
}
mLinePathList.add(pathline);
canvas.drawPath(pathline, mLinePaint);
}
lineStarted = false;//
}
//
if(i == mJcharts.size()-1 && lineStarted) {
PathMeasure pathMeasure = new PathMeasure(pathline, false);
if(i>0 && pathMeasure.getLength()<0.001f) {
pathline.lineTo(midPointF.x, midPointF.y+0.001f);
}
mLinePathList.add(pathline);
canvas.drawPath(pathline, mLinePaint);
}
}
mPrePoint = midPointF;
}
lineStarted = false;
return false;
}
/**
*
*
* @param jchartList
*/
@Override
public void aniChangeData(List<Jchart> jchartList){
if(mWidth<=0) {
throw new RuntimeException("after onsizechange");
}
mSliding = 0;//
mState = aniChange;
if(jchartList != null && jchartList.size() == mAllLastPoints.size()) {
mAllLastPoints.clear();
mSelected = -1;
mJcharts.clear();
mJcharts.addAll(jchartList);
for(int i = 0; i<mJcharts.size(); i++) {
Jchart jchart = mJcharts.get(i);
jchart.setIndex(i);
PointF allPoint = mAllPoints.get(i);
//
mAllLastPoints.add(new PointF(allPoint.x, allPoint.y));
}
findTheBestChart();
refreshChartArea();
aniShowChar(0, 1, new LinearInterpolator());
}else {
throw new RuntimeException("aniChangeDatacmddata");
}
}
@Override
protected void refreshOthersWithEveryChart(int i, Jchart jchart){
if(mGraphStyle == LINE) {
mAllPoints.add(jchart.getMidPointF());
if(mAllLastPoints.get(i).y == -1) {
if(mShowFromMode == SHOWFROMBUTTOM) {
mAllLastPoints.get(i).y = mChartArea.bottom;//0
}else if(mShowFromMode == SHOWFROMTOP) {
mAllLastPoints.get(i).y = mChartArea.top;//0
}else if(mShowFromMode == SHOWFROMMIDDLE) {
mAllLastPoints.get(i).y = ( mChartArea.bottom+mChartArea.top )/2;//0
}
}
}else {
if(BuildConfig.DEBUG) {
Log.e(TAG, " ");
}
//continue; //continue
mAllPoints.add(jchart.getMidPointF());
if(mAllLastPoints.get(i).y == -1) {
mAllLastPoints.get(i).y = mChartArea.bottom;//0
}
}
}
/**
*
*/
protected void refreshExcels(){
mAllPoints.clear();
super.refreshExcels();
refreshLinepath();
mChartRithtest_x = mJcharts.get(mJcharts.size()-1).getMidPointF().x;
mChartLeftest_x = mJcharts.get(0).getMidPointF().x;
if(mJcharts.size()>1) {
mBetween2Excel = mJcharts.get(1).getMidPointF().x-mJcharts.get(0).getMidPointF().x;
}
}
private void refreshLinepath(){
// path
mLinePath.reset();
mShadeAreaPath.reset();
//
if(mLineStyle == LINE_CURVE) {
for(int i = 0; i<mAllPoints.size()-1; i++) {
PointF startPoint = mAllPoints.get(i);
PointF endPoint = mAllPoints.get(i+1);//
if(mLinePath.isEmpty()) {
mLinePath.moveTo(startPoint.x, startPoint.y);
mShadeAreaPath.moveTo(startPoint.x, startPoint.y);
}
DrawHelper.pathCubicTo(mLinePath, startPoint, endPoint);
DrawHelper.pathCubicTo(mShadeAreaPath, startPoint, endPoint);
}
}else {
for(PointF allPoint : mAllPoints) {
if(mLinePath.isEmpty()) {
mLinePath.moveTo(allPoint.x, allPoint.y);
mShadeAreaPath.moveTo(allPoint.x, allPoint.y);
}else {
mLinePath.lineTo(allPoint.x, allPoint.y);
mShadeAreaPath.lineTo(allPoint.x, allPoint.y);
}
}
}
mShadeAreaPath.lineTo(mChartRithtest_x, mChartArea.bottom);
mShadeAreaPath.lineTo(mChartLeftest_x, mChartArea.bottom);
mShadeAreaPath.close();
}
@Override
public void feedData(@NonNull List<Jchart> jchartList){
super.feedData(jchartList);
}
public void feedData(float... data){
ArrayList<Jchart> jchartList = new ArrayList<>(data.length);
for(float v : data) {
Jchart jchart = new Jchart(v, mNormalColor);
jchartList.add(jchart);
}
super.feedData(jchartList);
}
public void aniShow_growing(){
if(mJcharts.size()<=0) {
if(BuildConfig.DEBUG) {
Log.e(TAG, " ");
}
return;
}
mState = -1;
if(mGraphStyle == LINE) {
if(mLineShowStyle == LINESHOW_ASWAVE) {
aswaveAniTrigger();
}else if(mLineMode == LINE_DASH_0 || mLineMode == LINE_JUMP0 ||
mLineShowStyle == LINESHOW_FROMLINE || mLineShowStyle == LINESHOW_FROMCORNER) {
if(mLineMode == LINE_DASH_0 || mLineMode == LINE_JUMP0) {
//0 ASWAVE FROMLINE
mLineShowStyle = LINESHOW_FROMLINE;
if(BuildConfig.DEBUG) {
Log.d(TAG, "aniShow_growing change showstyle 2 fromline");
}
}
if(mShowFromMode == SHOWFROMMIDDLE) {
aniShowChar(0, 1, new AccelerateInterpolator());
}else {
aniShowChar(0, 1);
}
}else if(mLineShowStyle == LINESHOW_SECTION) {
mAniLinePath.reset();
mAniShadeAreaPath.reset();
aniShowChar(0, mJcharts.size()-1, new LinearInterpolator(), 5000, true);
}else if(mLineShowStyle == LINESHOW_DRAWING) {
mAniLinePath.reset();
mAniShadeAreaPath.reset();
mPathMeasure = new PathMeasure(mLinePath, false);
mPathMeasure.getPosTan(0, mCurPosition, null);
aniShowChar(0, mPathMeasure.getLength(), new LinearInterpolator(), 3000);
}
}else {
if(mJcharts.size()>0) {
if(mBarShowStyle == BARSHOW_ASWAVE) {
aswaveAniTrigger();
}else if(mBarShowStyle == BARSHOW_SECTION) {
aniShowChar(0, mJcharts.size()-1, new LinearInterpolator(), ( mJcharts.size()-1 )*300, true);
}else {
aniShowChar(0, 1, new LinearInterpolator());
}
}
}
}
private void aswaveAniTrigger(){
for(Jchart jchart : mJcharts) {
jchart.setAniratio(0);
}
aniShowChar(0, mJcharts.size()-1, new LinearInterpolator(), ( mJcharts.size()-1 )*250, true);
}
@Override
protected void onAnimationUpdating(ValueAnimator animation){
if(mState == aniChange) {
floatChangeAni(animation);
}else if(mGraphStyle == BAR) {
if(mBarShowStyle == BARSHOW_ASWAVE || mBarShowStyle == BARSHOW_SECTION) {
if(animation.getAnimatedValue() instanceof Integer) {
mAniRatio = (int)animation.getAnimatedValue();
mJcharts.get(( (int)mAniRatio )).aniHeight(this, 0, new AccelerateInterpolator());
}
}else {
floatChangeAni(animation);
}
}else {
if(mLineMode == LINE_EVERYPOINT) {
if(mLineShowStyle == LINESHOW_FROMLINE || mLineShowStyle == LINESHOW_FROMCORNER) {
floatChangeAni(animation);
}else if(mLineShowStyle == LINESHOW_ASWAVE || mLineShowStyle == LINESHOW_SECTION) {
intChangeAni(animation);
}else {
if(animation.getAnimatedValue() instanceof Float) {
mAniRatio = (float)animation.getAnimatedValue();
if(mGraphStyle == LINE) {
if(mLineShowStyle == LINESHOW_DRAWING && mState != aniChange) {
//mCurPositionmCurPosition = new float[2];
mPathMeasure.getPosTan(mAniRatio, mCurPosition, null);
}
}
}
}
}else {
if(mLineShowStyle == LINESHOW_FROMLINE) {
floatChangeAni(animation);
}else {
//
intChangeAni(animation);
}
}
}
postInvalidate();
}
private void intChangeAni(ValueAnimator animation){
if(animation.getAnimatedValue() instanceof Integer) {
int curr = (int)animation.getAnimatedValue();
mJcharts.get(curr).aniHeight(this);
mAniRatio = curr;
}
}
private void floatChangeAni(ValueAnimator animation){
if(animation.getAnimatedValue() instanceof Float) {
mAniRatio = (float)animation.getAnimatedValue();
}
}
@Override
protected void onDetachedFromWindow(){
super.onDetachedFromWindow();
mAniShadeAreaPath = null;
mLinePath = null;
mShaderColors = null;
mPathMeasure = null;
mCurPosition = null;
mAllPoints = null;
mAllLastPoints = null;
mAniLinePath = null;
}
@Override
public void setInterval(float interval){
super.setInterval(interval);
refreshChartSetData();
}
/**
*
*
* @param lineWidth
*/
public void setLineWidth(float lineWidth){
mLineWidth = lineWidth;
}
/**
*
*
* @param canvas
* @param excel
*/
protected void drawSelectedText(Canvas canvas, Jchart excel){
CalloutHelper.drawCalloutActual(canvas, excel, true, mLineWidth, mChartArea.right, mSelectedTextBgPaint,
mSelectedTextPaint, mScrollAble);
}
/**
*
*
*
* @param colors
*/
public void setPaintShaderColors(@ColorInt int... colors){
mShaderColors = colors;
if(mWidth>0) {
paintSetShader(mLinePaint, mShaderColors);
paintSetShader(mBarPaint, mShaderColors);
}
}
public void setShaderAreaColors(@ColorInt int... colors){
mShaderAreaColors = colors;
if(mWidth>0) {
paintSetShader(mShaderAreaPaint, mShaderAreaColors);
postInvalidate();
}
}
public float getAniRatio(){
return mAniRatio;
}
public void setAniRatio(float aniRatio){
this.mAniRatio = aniRatio;
}
public float getAniRotateRatio(){
return mAniRotateRatio;
}
public void setAniRotateRatio(float aniRotateRatio){
mAniRotateRatio = aniRotateRatio;
invalidate();
}
@Override
protected void onAttachedToWindow(){
super.onAttachedToWindow();
if(BuildConfig.DEBUG) {
Log.e(TAG, "onAttachedToWindow ");
}
}
@Override
public void setSelectedMode(@SelectedMode int selectedMode){
mSelectedMode = selectedMode;
if(mWidth>0) {
refreshChartArea();
}
}
public void setLineStyle(@LineStyle int lineStyle){
mLineStyle = lineStyle;
if(mWidth>0) {
refreshLinepath();
}
}
/**
* -1
*
* @param lineShowStyle
* one of {@link LineShowStyle}
*/
public void setLineShowStyle(@LineShowStyle int lineShowStyle){
if(mValueAnimator.isRunning()) {
mValueAnimator.cancel();
if(mLineShowStyle == LINESHOW_ASWAVE) {
for(Jchart jchart : mJcharts) {
jchart.setAniratio(1);
}
}
mAniRatio = 1;
}
mLineShowStyle = lineShowStyle;
}
public void setBarShowStyle(@BarShowStyle int barShowStyle){
if(mValueAnimator.isRunning()) {
mValueAnimator.cancel();
if(mBarShowStyle == BARSHOW_ASWAVE) {
for(Jchart jchart : mJcharts) {
jchart.setAniratio(1);
}
}
}
mBarShowStyle = barShowStyle;
}
/**
* fromline
*
* @param showFromMode
* one of {@link ShowFromMode}
*/
public void setShowFromMode(@ShowFromMode int showFromMode){
mShowFromMode = showFromMode;
}
public int getLineMode(){
return mLineMode;
}
/**
* linemode0 aswavefromline
*
* @param lineMode
*/
public void setLineMode(@LineMode int lineMode){
mLineMode = lineMode;
if(mValueAnimator.isRunning()) {
mValueAnimator.cancel();
}
}
public float getLinePointRadio(){
return mLinePointRadio;
}
public void setLinePointRadio(@DimenRes int linePointRadio){
mLinePointRadio = linePointRadio;
}
public float getLineWidth(){
return mLineWidth;
}
@Override
public void setNormalColor(@ColorInt int normalColor){
super.setNormalColor(normalColor);
mLinePaint.setColor(mNormalColor);
}
}
// barwidth
//
//
// 1 mVisibleNums
// 2 mVisibleNums mExecels
//
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/graph/JcoolGraph.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 9,338 |
```java
package com.jonas.jgraph.models;
import java.util.Random;
/**
* @author yun.
* @date 2016/6/8
* @des [ ]
* @since [path_to_url
* <p><a href="path_to_url">github</a>
*/
public class Apiece {
/**
*
*/
private String describe;
/**
*
*/
private Float num;
/**
*
*/
private int pieColor = Integer.MAX_VALUE;
/**
*
*/
private float startAngle;
/**
*
*/
private float sweepAngle;
public Apiece(String describe, Float num, int pieColor, float startAngle, float sweepAngle) {
this.describe = describe;
this.num = num;
this.pieColor = pieColor;
this.startAngle = startAngle;
this.sweepAngle = sweepAngle;
}
public Apiece(String describe, Float num, int pieColor) {
super();
this.describe = describe;
this.num = num;
this.pieColor = pieColor;
}
public Apiece(int pieColor, Float num) {
this.pieColor = pieColor;
this.num = num;
}
/**
*
*
* @param num
*/
public Apiece(Float num) {
this.pieColor = getRanColor();
this.num = num;
}
public String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
public Float getNum() {
return num;
}
public void setNum(Float num) {
this.num = num;
}
public int getPieColor() {
return pieColor;
}
public void setPieColor(int pieColor) {
this.pieColor = pieColor;
}
public float getStartAngle() {
return startAngle;
}
public void setStartAngle(float startAngle) {
this.startAngle = startAngle;
}
public float getSweepAngle() {
return sweepAngle;
}
public void setSweepAngle(float sweepAngle) {
this.sweepAngle = sweepAngle;
}
private int getRanColor() {
Random random = new Random();
return 0xff000000 | random.nextInt(0x00ffffff);
}
}
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/models/Apiece.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 514 |
```java
package com.jonas.jgraph.models;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RectF;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import java.text.DecimalFormat;
import static android.content.ContentValues.TAG;
/**
* @author yun.
* @date 2016/6/8
* @des []
* @since [path_to_url
* <p><a href="path_to_url">github</a>
*/
public class Jchart implements Cloneable {
private String mShowMsg;
private int index; //
private float mWidth;//
private float mHeight;//y
private PointF mStart = new PointF();//
private float mMidX;// x
private int mColor = -1;
private float mNum; //
private float mMax; //
private float percent;//
private String textMsg; //
private String mXmsg; //
private float mUpper;
private float mLower;
private float mLowStart;
private String tag;
private float mStandedHeight = 0;//
private boolean mOp;
private boolean mActualOp;
private boolean mPathover;
private Path mStantedRec = new Path();//
private Path mActualRec = new Path(); //
private Path mOVerRec = new Path(); //
private float mAniratio = 1;
private ValueAnimator mValueAnimator = ValueAnimator.ofFloat(0, 1);
;
private long DURATION = 700;
// private TimeInterpolator INTERPOLATOR = new BounceInterpolator();
private TimeInterpolator INTERPOLATOR = new OvershootInterpolator(3);
private float mHeightRatio = 1;
// public boolean mTopRound = true;
public boolean mTopRound;
public Jchart(float num, int color){
this(0, num, "", color);
}
public Jchart(float lower, float num, int color){
this(lower, lower+num, "", color);
}
public Jchart(float lower, float upper, String mXmsg){
this(lower, upper, mXmsg, Color.GRAY);
}
public Jchart(float lower, float upper, String mXmsg, int color){
mUpper = upper;
mLower = lower;
mHeight = mNum = upper-lower;
mStart.y = 0;
this.mColor = color;
this.mXmsg = TextUtils.isEmpty(mXmsg) ? new DecimalFormat("##").format(mHeight) : mXmsg;
mShowMsg = new DecimalFormat("##").format(mUpper);
}
public RectF getRectF(){
float bottom = mStart.y-( mLower-mLowStart )*mHeightRatio*mAniratio;
bottom = bottom<mStart.y ? bottom : mStart.y;
float top = mStart.y-( mUpper-mLowStart )*mHeightRatio*mAniratio;
top = top<mStart.y ? top : mStart.y;
return new RectF(mStart.x, top, mStart.x+mWidth, bottom);
// return new RectF(mStart.x, mStart.y - (mUpper - mLowStart) * mHeightRatio * mAniratio, mStart.x + mWidth, mStart.y - (mLower - mLowStart) * mHeightRatio * mAniratio);
}
/**
*
*
* @return
*/
public Path getRectFPath(){
// if (mHeight > 0) {
if(!mActualOp || mAniratio<1 && mHeight>0) {
mActualRec = new Path();
RectF[] helpRectFs = getHelpRectFs(mLower, mUpper, mAniratio);
RectF rectF = helpRectFs[1];
RectF rectCircle = helpRectFs[0];
mActualOp = extraPath(mActualRec, mHeight*mHeightRatio*mAniratio, mActualOp, rectF, rectCircle);
}
return mActualRec;
}
public Path getRectFPath(float mLower, float mUpper){
mActualRec = new Path();
RectF[] helpRectFs = getHelpRectFs(mLower, mUpper, mAniratio);
RectF rectF = helpRectFs[1];
RectF rectCircle = helpRectFs[0];
mActualOp = extraPath(mActualRec, mHeight*mHeightRatio*mAniratio, mActualOp, rectF, rectCircle);
return mActualRec;
}
private RectF[] getHelpRectFs(float mLower, float mUpper, float mAniratio){
RectF[] helpRectfs = new RectF[2];
mAniratio = mAniratio>0.9 ? 1 : mAniratio;
float bottom = mStart.y-( mLower-mLowStart )*mHeightRatio*mAniratio;
float top = mStart.y-( mUpper-mLowStart )*mHeightRatio*mAniratio+mWidth/2f;
bottom = bottom<mStart.y ? bottom : mStart.y;
top = top<mStart.y ? top : mStart.y;
helpRectfs[1] = new RectF(mStart.x, top, mStart.x+mWidth, bottom);
helpRectfs[0] = new RectF(mStart.x, top-mWidth/2f, mStart.x+mWidth, top+mWidth/2f);
return helpRectfs;
}
private boolean extraPath(Path mOVerRec, float mOverHeight, boolean op, RectF secRectF, RectF firstRectFC){
if(mOverHeight>mWidth/2f) {
Path rec = new Path();
rec.moveTo(secRectF.left, secRectF.top);
rec.lineTo(secRectF.left, secRectF.bottom);
rec.lineTo(secRectF.right, secRectF.bottom);
rec.lineTo(secRectF.right, secRectF.top);
mOVerRec.addPath(rec);
mOVerRec.addArc(firstRectFC, 180, 180);
return true;
}else {
firstRectFC.bottom -= ( mWidth-2*mOverHeight );
mOVerRec.addArc(firstRectFC, 180, 180);
mOVerRec.close();
return true;
}
}
/**
*
*
* @return
*/
public RectF getOverRectF(){
float mOverHeight = ( mHeight-mStandedHeight )*mHeightRatio*mAniratio;
mOverHeight = mOverHeight>0 ? mOverHeight : 0;
if(mOverHeight>0) {
return new RectF(mStart.x, mStart.y-mHeight*mHeightRatio*mAniratio, mStart.x+mWidth,
mStart.y-mStandedHeight*mHeightRatio*mAniratio);
}else {
return new RectF(0, 0, 0, 0);
}
}
/**
*
*
* @return
*/
public Path getOverRectFPath(){
float mOverHeight = ( mHeight-mStandedHeight )*mHeightRatio*mAniratio;
if(!mPathover || mAniratio<1 && mOverHeight>0) {
RectF rectF = new RectF(mStart.x, mStart.y-mHeight*mHeightRatio*mAniratio+mWidth/2f, mStart.x+mWidth,
mStart.y-mStandedHeight*mHeightRatio*mAniratio);
RectF[] helpRectFs = getHelpRectFs(mLower, mUpper, mAniratio);
RectF rectCircle = helpRectFs[0];
mPathover = extraPath(mOVerRec, mOverHeight, false, rectF, rectCircle);
}
return mOVerRec;
}
/**
*
*
* @return
*/
public RectF getStandedRectF(){
return new RectF(mStart.x, mStart.y-mStandedHeight*mHeightRatio, mStart.x+mWidth, mStart.y);
}
/**
*
*
* @return
*/
public Path getStandedPath(){
if(!mOp || mAniratio<1 && mStandedHeight>0) {
mStantedRec = new Path();
RectF[] helpRectFs = getHelpRectFs(mLower, mUpper, mAniratio);
RectF rectF = helpRectFs[1];
RectF rectCircle = helpRectFs[0];
mOp = extraPath(mStantedRec, mStandedHeight*mHeightRatio, mOp, rectF, rectCircle);
}
return mStantedRec;
}
/**
*
*
* @return
*/
public PointF getMidPointF(){
float top = mStart.y-( mUpper-mLowStart )*mHeightRatio*mAniratio;
top = top<mStart.y ? top : mStart.y;
return new PointF(getMidX(), top);
}
public String getTextMsg(){
return textMsg;
}
public Jchart setTextMsg(String textMsg){
this.textMsg = textMsg;
return this;
}
public float getWidth(){
return mWidth;
}
public Jchart setWidth(float width){
this.mWidth = width;
return this;
}
public float getHeight(){
//
return mHeight*mHeightRatio;
}
public Jchart setHeight(float height){
this.mHeight = height>0 ? height : 0;
if(mHeight+mLower != mUpper) {
setUpper(mHeight+mLower);
}
openRpath();
return this;
}
public float getHeightRatio(){
return mHeightRatio;
}
public Jchart setHeightRatio(float heightRatio){
mHeightRatio = heightRatio;
openRpath();
return this;
}
public PointF getStart(){
return mStart;
}
public Jchart setStart(PointF start){
this.mStart = start;
return this;
}
public float getMidX(){
if(null != mStart) {
mMidX = mStart.x+mWidth/2;
}else {
throw new RuntimeException("mStart ");
}
return mMidX;
}
public Jchart setMidX(float midX){
this.mMidX = midX;
return this;
}
public int getColor(){
return mColor;
}
public Jchart setColor(int color){
mColor = color;
return this;
}
public float getNum(){
return mNum;
}
public Jchart setNum(float num){
this.mNum = num;
return this;
}
public float getMax(){
return mMax;
}
public Jchart setMax(float max){
this.mMax = max;
return this;
}
public String getXmsg(){
return mXmsg;
}
public Jchart setXmsg(String xmsg){
this.mXmsg = xmsg;
return this;
}
public float getUpper(){
return mUpper;
}
/**
* lower
*
* @param upper
*/
public Jchart setUpper(float upper){
if(upper<mLower) {
upper = mLower;
Log.e(TAG, "lower > upper than lower = upper = "+mUpper);
}
mUpper = upper;
mHeight = mUpper-mLower;
if("\\d+".matches(mXmsg)) {
if(Float.parseFloat(mXmsg) == mHeight) {
this.mXmsg = new DecimalFormat("##").format(mUpper-mLower);
}
mShowMsg = new DecimalFormat("##.#").format(mUpper);
}
openRpath();
return this;
}
public float getLower(){
return mLower;
}
/**
*
*
* @param lower
*/
public Jchart setLower2(float lower){
if(mLower == lower) {
return this;
}
mLower = lower;
setUpper(mHeight+mLower);
openRpath();
return this;
}
/**
* upper
*
* @param lower
*/
public Jchart setLower(float lower){
if(mLower == lower) {
return this;
}
if(lower>mUpper) {
Log.e(TAG, "lower > upper than lower = upper = "+mUpper);
lower = mUpper;
}
openRpath();
mLower = lower;
setHeight(mUpper-mLower);
return this;
}
public int getIndex(){
return index;
}
public Jchart setIndex(int index){
this.index = index;
return this;
}
public String getShowMsg(){
return mShowMsg;
}
public Jchart setShowMsg(String showMsg){
mShowMsg = showMsg;
return this;
}
@Override
public Object clone(){
Jchart clone = null;
try {
clone = (Jchart)super.clone();
//
clone.mStart = new PointF(mStart.x, mStart.y);
clone.mStantedRec = new Path(mStantedRec);//
clone.mActualRec = new Path(mActualRec); //
clone.mOVerRec = new Path(mOVerRec); //
}catch(CloneNotSupportedException e) {
Log.e(TAG, " ");
}
return clone;
}
public String getTag(){
return tag;
}
public Jchart setTag(String tag){
this.tag = tag;
return this;
}
public float getPercent(){
return percent;
}
public Jchart setPercent(float percent){
this.percent = percent;
return this;
}
public float getAniratio(){
return mAniratio;
}
public Jchart setAniratio(float aniratio){
mValueAnimator.cancel();
mAniratio = aniratio;
return this;
}
public float getLowStart(){
return mLowStart;
}
/**
* 0
*
* @param lowStart
*/
public Jchart setLowStart(float lowStart){
mLowStart = lowStart;
return this;
}
public Jchart aniHeight(final View view, float from, TimeInterpolator interpolator){
if(!mValueAnimator.isRunning() && mAniratio<0.8) {
mValueAnimator.setFloatValues(from, 1);
mValueAnimator.setDuration(DURATION);
mValueAnimator.setInterpolator(interpolator);
mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation){
mAniratio = (float)animation.getAnimatedValue();
view.postInvalidate();
setPercent(mAniratio);
}
});
mValueAnimator.start();
}
return this;
}
public Jchart aniHeight(View view){
return aniHeight(view, 0, INTERPOLATOR);
}
public Jchart draw(Canvas canvas, Paint paint, boolean point){
if(point) {
canvas.drawPoint(getMidPointF().x, getMidPointF().y, paint);
}else {
if(mTopRound) {
canvas.drawPath(getRectFPath(), paint);
}else {
canvas.drawRect(getRectF(), paint);
}
}
return this;
}
public Jchart draw(Canvas canvas, Paint paint, int radius){
if(mTopRound) {
canvas.drawPath(getRectFPath(), paint);
}else {
canvas.drawRoundRect(getRectF(), radius, radius, paint);
}
return this;
}
public void setTopRound(boolean topRound){
this.mTopRound = topRound;
}
public float getTopest(){
return mUpper>mStandedHeight ? mUpper : mStandedHeight;
}
public void setStandedHeight(float standedHeight){
mStandedHeight = standedHeight;
}
private void openRpath(){
mOp = false;
mActualOp = false;
mPathover = false;
}
}
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/models/Jchart.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 3,549 |
```java
package com.jonas.jgraph.graph;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.DashPathEffect;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import com.jonas.jgraph.models.NExcel;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author yun.
* @date 2016/7/11
* @des [ style Paint.Style.STROKE]
* @since [path_to_url
* <p><a href="path_to_url">github</a>
*/
public class NChart extends View implements ValueAnimator.AnimatorUpdateListener, Animator.AnimatorListener {
private int mWidth;
private int mHeight;
/**
* x y
*/
private float mHCoordinate = 0;
/**
* x x
*/
private float mAbove;
/**
*
*/
private int mSelected = -1;
private float mDownX;
private boolean moved;
// margin
private float mTextMarging;
private float mTextSize = 15;
private int mBarStanded = 0;
/**
*
*/
private float mSugHeightest;
/**
*
*/
private float mHeightRatio = 1;
/**
*
*/
private boolean mScrollAble = true;
//---------------------------
private Paint mLinePaint;
private Paint mLinePaint2;
/**
*
*/
private Paint mExecelPaint;
private Paint mTextPaint;
/**
*
*/
private Paint mAbscissaPaint;
private Paint mTextBgPaint;
private Paint mPointPaint;
private Path pathLine = new Path();
/**
*
*/
private int mActivationColor = Color.RED;
/**
*
*/
private int mNormalColor = Color.DKGRAY;
/**
*
*/
private int mAbscissaMsgColor = Color.parseColor("#556A73");
private int mTextBgColor = Color.parseColor("#556A73");
private int mPointColor = Color.parseColor("#CC6500");
/**
*
*/
private int[] mShaderColors;
private DecimalFormat mFormat;
/**
*
*/
private int selectedModed = SelectedMode.selectedActivated;
private Context mContext;
/**
*
*/
private int mTouchSlop;
/**
*
*/
private float mInterval;
/**
*
*/
private List<NExcel> mExcels = new ArrayList<>();
/**
*
*/
private float mBarWidth = 0;
/**
*
*/
private float mAbscissaMsgSize;
private int mFixedNums;//
/**
*
*/
private float mSliding = 0;
//-----------------
private float ratio = 1;
private long animateTime = 1600;
private ValueAnimator mVa;
/**
*
*/
private boolean mCrosses;
//-------------
private Interpolator mInterpolator = new DecelerateInterpolator();//
private PathEffect pathEffect = null;
private float phase = 0;//
private Rect mBounds;
private boolean mNeedLineEffict = false;
/**
*
*/
private float mLinePointRadio = 0;
private int mTextColor = Color.parseColor("#556A73");
// new AccelerateInterpolator()
// new AnticipateInterpolator()
// new BounceInterpolator()
// new OvershootInterpolator()
/**
*
*/
// private int mGraphStyle = GraphStyle.BAR_LINE;
private int mChartStyle = ChartStyle.BAR;
private int mTextAniStyle = TextAniStyle.ANIDOWN;
/**
*
*/
private int mBarAniStyle = ChartAniStyle.BAR_DISPERSED;
/**
*
*/
private int mLineAniStyle = ChartAniStyle.BAR_DOWN;
private float mBarRadio = 0;
private float tempTextMargin;
public interface ChartStyle {
static final int BAR = 1;
static final int LINE = 2;
static final int BAR_LINE = 4;
static final int CLOSELINE = 5;
}
public interface SelectedMode {
/**
*
*/
int selectedActivated = 0;
/**
*
*/
int selecetdMsgShow = 1;
}
public interface TextAniStyle {
static final int ANIUP = 0;
static final int ANIDOWN = 1;
}
public interface ChartAniStyle {
static final int BAR_UP = 0;
static final int BAR_RIGHT = 1;
static final int BAR_DOWN = 2;
/**
*
*/
static final int BAR_DISPERSED = 5;
static final int LINE_RIPPLE = 3;
static final int LINE_CONNECT = 4;
}
public NChart(Context context) {
super(context);
init(context);
}
public NChart(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public NChart(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (attrs != null) {
// TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MPieView, defStyleAttr, 0);
// pieInterWidth = (int)typedArray.getDimension(R.styleable.MPieView_pieInterColor, 0);
// backColor = typedArray.getColor(R.styleable.MPieView_piebackground, Color.WHITE);
// specialAngle = typedArray.getInt(R.styleable.MPieView_specialAngle, 0);
// PieSelector = typedArray.getBoolean(R.styleable.MPieView_PieSelector, true);
// typedArray.recycle();
}
init(context);
}
private void init(Context context) {
mContext = context;
initData();
//
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mExecelPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTextAlign(Paint.Align.CENTER);//
mTextPaint.setTextSize(mTextSize);
mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mLinePaint.setStrokeWidth(2);
mLinePaint.setStyle(Paint.Style.STROKE);// style Paint.Style.STROKE
mFormat = new DecimalFormat("##.##");
mTextBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextBgPaint.setColor(mTextBgColor);
mPointPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mAbscissaPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mAbscissaPaint.setTextSize(mAbscissaMsgSize);
mAbscissaPaint.setColor(mAbscissaMsgColor);
mAbscissaPaint.setTextAlign(Paint.Align.CENTER);//
//
mLinePaint2 = new Paint(Paint.ANTI_ALIAS_FLAG);
mLinePaint2.setPathEffect(new CornerPathEffect(25));//
mLinePaint2.setShader(new LinearGradient(0, 20, 0, mHeight, Color.RED, Color.GREEN, Shader.TileMode.CLAMP));
// height
}
/**
*
*/
private void initData() {
mBarWidth = dip2px(36);
mInterval = dip2px(20);
tempTextMargin = mTextMarging = dip2px(4);
mTextSize = sp2px(15);
mAbscissaMsgSize = sp2px(15);
// mLinePointRadio = dip2px(4);
mAbove = dip2px(5);
mBounds = new Rect();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mHeight = h;
mHCoordinate = mHeight - Math.abs(2 * mAbscissaMsgSize);
(w);
// //
// mHeightRatio = (mHCoordinate - 2 * mTextSize - mAbove - mTextMarging - mLinePointRadio - 5) / mSugHeightest;
if (mExcels.size() > 0) {
();
}
mWidth = w;
if (mExcels.size()>0) {
animateExcels();
}
}
private void (int w) {
//
if (!mScrollAble) {
if (mFixedNums != 0 && mChartStyle == ChartStyle.BAR) {
// mBarWidth = (w - 2 * (mFixedNums - 1)) / mFixedNums;
// mInterval = (w - mBarWidth * mJcharts.size()) / (mJcharts.size() - 1);
mBarWidth = (w - 2 * (mFixedNums + 1)) / mFixedNums;
mInterval = (w - mBarWidth * mExcels.size()) / (mExcels.size() + 1);
} else {
// 2
mInterval = 2;
mBarWidth = (w - mInterval * (mExcels.size() + 1)) / mExcels.size();
}
}
}
private void () {
if (mHCoordinate > 0) {
//
mHeightRatio = (mHCoordinate - 2 * mTextSize - mAbove - mTextMarging - mLinePointRadio - 5) / mSugHeightest;
for (int i = 0; i < mExcels.size(); i++) {
NExcel nExcel = mExcels.get(i);
nExcel.setHeight(nExcel.getHeight() * mHeightRatio);
nExcel.setWidth(mBarWidth);
PointF start = nExcel.getStart();
start.x = mInterval * (i + 1) + mBarWidth * i;
start.y = mHCoordinate - mAbove - nExcel.getLower();
//nExcel.setColor(mNormalColor);
}
}
}
private void refreshExcels() {
if (mHCoordinate > 0) {
for (int i = 0; i < mExcels.size(); i++) {
NExcel nExcel = mExcels.get(i);
nExcel.setWidth(mBarWidth);
PointF start = nExcel.getStart();
start.x = mInterval * (i + 1) + mBarWidth * i;
start.y = mHCoordinate - mAbove - nExcel.getLower();
//nExcel.setColor(mNormalColor);
}
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// drawSugExcel_BAR(canvas);
// drawSugExcel_CloseLINE(canvas);
// drawCoordinateAxes(canvas);
if (mChartStyle == ChartStyle.BAR) {
drawSugExcel_BAR(canvas);
} else if (mChartStyle == ChartStyle.LINE) {
drawSugExcel_LINE(canvas);
} else if (mChartStyle == ChartStyle.CLOSELINE) {
drawSugExcel_CloseLINE(canvas);
} else {
drawSugExcel_BAR(canvas);
drawSugExcel_LINE(canvas);
}
drawCoordinateAxes(canvas);
}
/**
*
*/
private void drawSugExcel_BAR(Canvas canvas) {
for (int i = 0; i < mExcels.size(); i++) {
NExcel excel = mExcels.get(i);
PointF start = excel.getStart();
if (selectedModed == SelectedMode.selectedActivated) {
//
if (null == mShaderColors) {
//
if (i != mSelected) {
mExecelPaint.setColor(mNormalColor);
} else {
mExecelPaint.setColor(mActivationColor);
}
} else {
//
if (i != mSelected) {
mExecelPaint.setShader(new LinearGradient(start.x, start.y - excel.getHeight(), start.x, start.y, mShaderColors[0], mShaderColors[1], Shader
.TileMode.CLAMP));
} else {
mExecelPaint.setShader(new LinearGradient(start.x, start.y - excel.getHeight(), start.x, start.y, mActivationColor, mShaderColors[1], Shader.TileMode.CLAMP));
}
}
drawSugExcel_text(canvas, excel, i, true);
} else {
//
if (null != mShaderColors) {
mExecelPaint.setShader(new LinearGradient(start.x, start.y - excel.getHeight
(), start.x, start.y, mShaderColors[0], mShaderColors[1], Shader
.TileMode
.CLAMP));
} else {
mExecelPaint.setColor(mNormalColor);
}
}
// canvas.drawRect(excel.getRectF(), mExecelPaint);
// canvas.drawRect(excel.getRectF().left, excel.getRectF().top * ratio, excel.getRectF().right,
// excel.getRectF().bottom, mExecelPaint);
// +
if (mBarAniStyle == ChartAniStyle.BAR_UP) {
//
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
canvas.drawRoundRect(excel.getRectF().left, excel.getRectF().bottom - (excel.getHeight()) * ratio,
excel.getRectF().right, excel.getRectF().bottom, mBarRadio, mBarRadio, mExecelPaint);
} else {
canvas.drawRect(excel.getRectF().left, excel.getRectF().bottom - (excel.getHeight()) * ratio,
excel.getRectF().right, excel.getRectF().bottom, mExecelPaint);
}
} else if (mBarAniStyle == ChartAniStyle.BAR_RIGHT) {
//
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
canvas.drawRoundRect(excel.getRectF().left, excel.getRectF().top,
excel.getRectF().left + (excel.getWidth()) * ratio, excel.getRectF().bottom, mBarRadio, mBarRadio, mExecelPaint);
} else {
canvas.drawRect(excel.getRectF().left, excel.getRectF().top,
excel.getRectF().left + (excel.getWidth()) * ratio, excel.getRectF().bottom, mExecelPaint);
}
// canvas.drawRect(excel.getRectF().left, excel.getRectF().top, excel.getRectF().right*ratio,
// excel.getRectF().bottom, mExecelPaint);
} else if (mBarAniStyle == ChartAniStyle.BAR_DOWN) {
//
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
canvas.drawRoundRect(excel.getRectF().left, excel.getRectF().top, excel.getRectF().right,
excel.getRectF().top + (excel.getHeight()) * ratio, mBarRadio, mBarRadio, mExecelPaint);
} else {
canvas.drawRect(excel.getRectF().left, excel.getRectF().top, excel.getRectF().right,
excel.getRectF().top + (excel.getHeight()) * ratio, mExecelPaint);
}
} else {
if (mBarStanded >= mExcels.size()) {
mBarStanded = mExcels.size() - 1;
}
NExcel sExcel = mExcels.get(mBarStanded);
//mBarStanded
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
canvas.drawRoundRect(sExcel.getRectF().left + (excel.getRectF().left - sExcel.getRectF().left) * ratio, excel.getRectF().top,
sExcel.getRectF().right + (excel.getRectF().right - sExcel.getRectF().right) * ratio,
excel.getRectF().bottom, mBarRadio, mBarRadio, mExecelPaint);
} else {
canvas.drawRect(sExcel.getRectF().left + (excel.getRectF().left - sExcel.getRectF().left) * ratio, excel.getRectF().top,
sExcel.getRectF().right + (excel.getRectF().right - sExcel.getRectF().right) * ratio,
excel.getRectF().bottom, mExecelPaint);
}
}
//
drawAbscissaMsg(canvas, excel);
}
if (selectedModed == SelectedMode.selecetdMsgShow && mSelected != -1 && ratio == 1) {
//
(canvas);
}
}
/**
*
*/
private void (Canvas canvas) {
mTextPaint.setColor(Color.WHITE);
NExcel excel = mExcels.get(mSelected);
PointF midPointF = excel.getMidPointF();
String msg = mFormat.format(excel.getUpper()) + excel.getUnit();
mTextPaint.getTextBounds(msg, 0, msg.length(), mBounds);
//
Path textBg = new Path();
float bgHeight = dip2px(6);
float bgWidth = dip2px(8);
// float textMarging = dip2px(3);//
// if (mGraphStyle == SugChart.GraphStyle.LINE) {
// textMarging = dip2px(2) + mLinePointRadio;
// }
// 43
// textBg.moveTo(midPointF.x, midPointF.y - mTextMarging);
// textBg.lineTo(midPointF.x - bgWidth / 2, midPointF.y - mTextMarging - bgHeight);
// textBg.lineTo(midPointF.x - mBounds.width() / 2 - bgWidth*3f/2, midPointF.y - mTextMarging - bgHeight);
// textBg.lineTo(midPointF.x - mBounds.width() / 2 - bgWidth*3f/2, midPointF.y - mTextMarging - bgHeight - mBounds.height() - bgHeight*2);
// textBg.lineTo(midPointF.x + mBounds.width() / 2 + bgWidth*3f/2, midPointF.y - mTextMarging - bgHeight - mBounds.height() - bgHeight*2);
// textBg.lineTo(midPointF.x + mBounds.width() / 2 + bgWidth*3f/2, midPointF.y - mTextMarging - bgHeight);
// textBg.lineTo(midPointF.x + bgWidth/2, midPointF.y - mTextMarging - bgHeight);
// textBg.close();
if (mChartStyle == ChartStyle.LINE) {
mTextMarging = tempTextMargin + mLinePointRadio;
} else {
mTextMarging = tempTextMargin;
}
//
textBg.moveTo(midPointF.x, midPointF.y - mTextMarging);
textBg.lineTo(midPointF.x - bgWidth / 2, midPointF.y - mTextMarging - bgHeight - 1.5f);
textBg.lineTo(midPointF.x + bgWidth / 2, midPointF.y - mTextMarging - bgHeight - 1.5f);
textBg.close();
canvas.drawPath(textBg, mTextBgPaint);
//
RectF rectF = new RectF(midPointF.x - mBounds.width() / 2 - bgWidth, midPointF.y - mTextMarging - bgHeight - mBounds.height() - bgHeight * 2
, midPointF.x + mBounds.width() / 2 + bgWidth, midPointF.y - mTextMarging - bgHeight);
float dffw = rectF.right - mWidth;
float msgX = midPointF.x;
float magin = 1;//
if (dffw > 0) {
rectF.right = rectF.right - dffw - magin;
rectF.left = rectF.left - dffw - magin;
msgX = midPointF.x - dffw - magin;
} else if (rectF.left < 0) {
rectF.right = rectF.right - rectF.left + magin;
msgX = midPointF.x - rectF.left + magin;
rectF.left = magin;
//
}
canvas.drawRoundRect(rectF, 3, 3, mTextBgPaint);
//
canvas.drawText(msg, msgX, midPointF.y - mTextMarging - bgHeight * 2, mTextPaint);
}
/**
* @param above true
*/
private void drawSugExcel_text(Canvas canvas, NExcel excel, int i, boolean above) {
PointF midPointF = excel.getMidPointF();
//SelectedMode.selectedActivated
if (mSelected == i) {
mTextPaint.setColor(mActivationColor);
} else {
mTextPaint.setColor(mTextColor);
}
float textMarging = mTextMarging;
if (mChartStyle == ChartStyle.LINE) {
textMarging = mTextMarging + mLinePointRadio;
}
// if(excel.getHeight()%2 == 0) {
// if(i%2 == 0) {
(canvas, mFormat.format(excel.getUpper()) + excel.getUnit(), midPointF.x, (above ? (midPointF.y - textMarging) : (midPointF.y + mTextSize + mLinePointRadio)) * ratio, (above ? (excel.getRectF().bottom - (excel.getHeight() + textMarging) * ratio) : (excel
.getRectF().bottom - (excel.getHeight() - mTextSize - mLinePointRadio) * ratio)));
//
if (excel.getLower() > 0 && mChartStyle == ChartStyle.BAR) {
(canvas, mFormat.format(excel.getLower()) + excel.getUnit(), midPointF.x, (excel.getStart().y + textMarging + mTextSize) * ratio, excel.getStart().y + excel.getLower() - (excel.getLower() - mTextSize) * ratio);
}
}
private void (Canvas canvas, String text, float x, float y, float y2) {
if (mTextAniStyle == TextAniStyle.ANIDOWN) {
//
canvas.drawText(text, x,
y, mTextPaint);
} else {
//
canvas.drawText(text, x,
y2, mTextPaint);
}
}
/**
*
*/
private void drawSugExcel_LINE(Canvas canvas) {
mLinePaint.setColor(mNormalColor);
if (mCrosses) {
//
PointF lineStart = mExcels.get(0).getMidPointF();
PointF lineEnd = mExcels.get(mExcels.size() - 1).getMidPointF();
canvas.drawLine(lineStart.x, mHeight / 2f, lineStart.x + (lineEnd.x - lineStart.x) * ratio, mHeight / 2f,
mLinePaint);
} else {
pathLine.reset();
(canvas);
if (null != mShaderColors && ratio == 1) {
//
(canvas);
}
if (mLinePointRadio > 0) {
//
(canvas);
}
// item
if (selectedModed == SelectedMode.selecetdMsgShow && mSelected != -1 && ratio == 1) {
(canvas);
}
}
}
private void (Canvas canvas) {
for (int i = 0; i < mExcels.size(); i++) {
NExcel excel = mExcels.get(i);
// PointF start = excel.getStart();
// if(mGraphStyle == GraphStyle.LINE) {
// start.x += mSliding;//
// }
PointF midPointF = excel.getMidPointF();
// canvas.drawPoint(midPointF.x, midPointF.y, mLinePaint);
if (i == 0) {
// pathLine.moveTo(midPointF.x, mHeight/2f);
pathLine.moveTo(midPointF.x, mHeight / 2f + (midPointF.y - mHeight / 2f) * ratio);
// pathLine.moveTo(midPointF.x, midPointF.y);
} else {
pathLine.lineTo(midPointF.x, mHeight / 2f + (midPointF.y - mHeight / 2f) * ratio);
// pathLine.quadTo(mJcharts.get(i-1).getMidPointF().x, mJcharts.get(i-1).getMidPointF().y, midPointF.x,
// midPointF.y);
}
if (selectedModed == SelectedMode.selectedActivated) {
//
//
if (i < mExcels.size() - 1) {
drawSugExcel_text(canvas, excel, i, excel.getMidPointF().y < mExcels.get(i + 1).getMidPointF().y);
} else {
drawSugExcel_text(canvas, excel, i, true);
}
}
//
drawAbscissaMsg(canvas, excel);
}
if (mNeedLineEffict) {
pathEffict();
}
canvas.drawPath(pathLine, mLinePaint);
}
private void (Canvas canvas) {
pathLine.lineTo(mExcels.get(mExcels.size() - 1).getMidX(), mHCoordinate);
pathLine.lineTo(mExcels.get(0).getMidX(), mHCoordinate);
pathLine.close();
mExecelPaint.setShader(new LinearGradient(0, 0, 0, mHCoordinate, mShaderColors[0], mShaderColors[1], Shader.TileMode.CLAMP));
canvas.drawPath(pathLine, mExecelPaint);
}
private void (Canvas canvas) {
for (int i = 0; i < mExcels.size(); i++) {
NExcel excel = mExcels.get(i);
PointF midPointF = excel.getMidPointF();
if (selectedModed == SelectedMode.selectedActivated) {
if (i == mSelected) {
mPointPaint.setColor(mActivationColor);
} else {
mPointPaint.setColor(mNormalColor);
}
} else {
mPointPaint.setColor(mPointColor);
}
canvas.drawCircle(midPointF.x, midPointF.y, mLinePointRadio, mPointPaint);
}
}
/**
*
*/
private void drawSugExcel_CloseLINE(Canvas canvas) {
mLinePaint.setColor(Color.RED);
mCrosses = false;
pathLine.reset();
pathLine.moveTo(mExcels.get(0).getMidPointF().x, mHCoordinate);
for (int i = 0; i < mExcels.size(); i++) {
NExcel excel = mExcels.get(i);
PointF midPointF = excel.getMidPointF();
canvas.drawPoint(midPointF.x, midPointF.y, mLinePaint);
pathLine.lineTo(midPointF.x, mHeight / 2f + (midPointF.y - mHeight / 2f) * ratio);
//
if (i < mExcels.size() - 1) {
drawSugExcel_text(canvas, excel, i, true);
} else {
drawSugExcel_text(canvas, excel, i, true);
}
//
drawAbscissaMsg(canvas, excel);
}
pathLine.lineTo(mExcels.get(mExcels.size() - 1).getMidPointF().x, mHCoordinate);
canvas.drawPath(pathLine, mLinePaint2);
}
/**
*
*/
private void drawAbscissaMsg(Canvas canvas, NExcel excel) {
mAbscissaPaint.setColor(mAbscissaMsgColor);
PointF midPointF = excel.getMidPointF();
//
canvas.drawText(excel.getXmsg(), midPointF.x, mHCoordinate + mTextMarging + mTextSize, mAbscissaPaint);
}
private void pathEffict() {
// PathEffect
// ComposePathEffect
// CornerPathEffect
// DashPathEffect(float[], phase) () phase
// DiscretePathEffect
// PathDashPathEffect(path,advance,phase,style)path advance phase
// SumPathEffect
// pathEffect = new CornerPathEffect(25); //
// pathEffect = new DashPathEffect(new float[]{10, 8, 5, 10}, phase); //
// ()
// pathEffect = new DiscretePathEffect(3f,6f); //
// Path p = new Path();
// p.addRect(0, 0, 6, 6, Path.Direction.CCW);
// if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// p.addArc(0, 0, 6, 6,0,180);
// }
// pathEffect = new PathDashPathEffect(p,18,phase,PathDashPathEffect.Style.ROTATE); //
pathEffect = new DashPathEffect(new float[]{10, 8, 5, 10}, phase); //
phase = ++phase % 50;//
mLinePaint.setPathEffect(pathEffect);
invalidate();
}
/**
*
*/
private void drawCoordinateAxes(Canvas canvas) {
mExecelPaint.setColor(Color.BLACK);
canvas.drawLine(0, mHCoordinate, mWidth, mHCoordinate, mExecelPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mExcels.size() > 0) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownX = event.getX();
break;
case MotionEvent.ACTION_MOVE:
if (ratio == 1) {//
float moveX = event.getX();
mSliding = moveX - mDownX;
if (Math.abs(mSliding) > mTouchSlop) {
// pathLine.reset();
moved = true;
mDownX = moveX;
if (mExcels.get(0).getStart().x + mSliding > mInterval || mExcels.get(mExcels.size() - 1)
.getStart().x + mBarWidth + mInterval + mSliding < mWidth) {
return true;
}
for (int i = 0; i < mExcels.size(); i++) {
NExcel excel = mExcels.get(i);
PointF start = excel.getStart();
start.x += mSliding;//
}
if (mScrollAble) {
invalidate();
}
}
}
break;
case MotionEvent.ACTION_UP:
if (!moved) {
PointF tup = new PointF(event.getX(), event.getY());
mSelected = clickWhere(tup);
invalidate();
}
moved = false;
mSliding = 0;
break;
}
}
return true;
}
/**
*
*/
private int clickWhere(PointF tup) {
for (int i = 0; i < mExcels.size(); i++) {
NExcel excel = mExcels.get(i);
PointF start = excel.getStart();
if (start.x > tup.x) {
return -1;
} else if (start.x <= tup.x) {
if (start.x + excel.getWidth() > tup.x && (start.y > tup.y && start.y - excel.getHeight() < tup.y)) {
return i;
}
}
}
return -1;
}
/**
*
*/
private int clickWhere2(PointF tup) {
int high = mExcels.size() - 1;
int low = 0;
int midle = mExcels.size() / 2;
while (low < high) {
midle = (low + high) / 2;
if (tup.x > mExcels.get(midle).getStart().x && tup.x < mExcels.get(midle).getStart().x + mBarWidth) {
NExcel nExcel = mExcels.get(midle);
if (tup.y < nExcel.getStart().y && tup.y > nExcel.getStart().y - nExcel.getHeight()) {
return midle;
}
} else if (tup.x > mExcels.get(midle).getStart().x) {
low = midle + 1;
} else {
high = midle - 1;
}
}
return -1;
}
/**
*
*/
public void cmdFill(NExcel... nExcels) {
cmdFill(Arrays.asList(nExcels));
}
/**
*
*/
public void cmdFill(List<NExcel> nExcelList) {
mExcels.clear();
for (NExcel nExcel : nExcelList) {
mSugHeightest = mSugHeightest > nExcel.getHeight() ? mSugHeightest : nExcel.getHeight();
}
for (int i = 0; i < nExcelList.size(); i++) {
NExcel nExcel = nExcelList.get(i);
nExcel.setWidth(mBarWidth);
PointF start = nExcel.getStart();
start.x = mInterval * (i + 1) + mBarWidth * i;
nExcel.setColor(mNormalColor);
mExcels.add(nExcel);
PointF midPointF = nExcel.getMidPointF();
if (i == 0) {
pathLine.moveTo(midPointF.x, midPointF.y);
} else {
pathLine.lineTo(midPointF.x, midPointF.y);
}
}
if (mWidth != 0) {
(mWidth);
();
postInvalidate();
}
}
private void animateExcels() {
if (mVa == null) {
mVa = ValueAnimator.ofFloat(0, 1).setDuration(animateTime);
mVa.addUpdateListener(this);
mVa.setInterpolator(mInterpolator);
mVa.addListener(this);
}
mVa.start();
}
@Override
public void onAnimationUpdate(ValueAnimator animation) {
ratio = (float) animation.getAnimatedValue();
postInvalidate();
}
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
if (ChartStyle.LINE == mChartStyle) {
if (mCrosses) {
mCrosses = false;
mVa.start();
}
}
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
public float getInterval() {
return mInterval;
}
/**
*
*/
public void setInterval(float interval) {
this.mInterval = interval;
refreshExcels();
}
public int getNormalColor() {
return mNormalColor;
}
/**
*
*/
public void setNormalColor(int normalColor) {
mNormalColor = normalColor;
}
public int getActivationColor() {
return mActivationColor;
}
/**
*
*/
public void setActivationColor(int activationColor) {
mActivationColor = activationColor;
}
public int getChartStyle() {
return mChartStyle;
}
/**
* +
*/
public void setChartStyle(int chartStyle) {
mChartStyle = chartStyle;
mCrosses = (mChartStyle == ChartStyle.LINE);
mVa.cancel();
mVa.start();
if (mChartStyle == ChartStyle.LINE) {
mTextMarging += mLinePointRadio / 2;
}
}
/**
* -
*/
public float getSliding() {
return mExcels.get(0).getStart().x - mInterval;
}
public void setSliding(float sliding) {
mSliding = sliding;
}
public float getBarWidth() {
return mBarWidth;
}
/**
*
*/
public void setBarWidth(float barWidth) {
mBarWidth = dip2px(barWidth);
refreshExcels();
}
public float getTextSize() {
return mTextSize;
}
/**
* x ()
*/
public void setTextSize(float textSize) {
mTextSize = sp2px(textSize);
mHCoordinate = mTextSize * 2;
}
public float getTextMarging() {
return mTextMarging;
}
public void setTextMarging(float textMarging) {
tempTextMargin = mTextMarging = dip2px(textMarging);
}
public float getHCoordinate() {
return mHCoordinate;
}
public float getRatio() {
return ratio;
}
public void setRatio(float ratio) {
this.ratio = ratio;
postInvalidate();
}
public float getAbove() {
return mAbove;
}
/**
* x
*
* @param above
*/
public void setAbove(float above) {
mAbove = above;
refreshExcels();
}
public int getBarStanded() {
return mBarStanded;
}
/**
*
*
* @param barStanded
*/
public void setBarStanded(int barStanded) {
mBarStanded = barStanded;
}
public int getTextAniStyle() {
return mTextAniStyle;
}
/**
*
*
* @param textAniStyle TextAniStyle
*/
public void setTextAniStyle(int textAniStyle) {
mTextAniStyle = textAniStyle;
}
public int getBarAniStyle() {
return mBarAniStyle;
}
/**
*
*
* @param barAniStyle ChartAniStyle
*/
public void setBarAniStyle(int barAniStyle) {
mBarAniStyle = barAniStyle;
if (barAniStyle == ChartAniStyle.BAR_DISPERSED) {
mInterpolator = new DecelerateInterpolator();//
} else if (barAniStyle == ChartAniStyle.BAR_DISPERSED) {
mInterpolator = new AccelerateInterpolator();//
}
}
public int getLineAniStyle() {
return mLineAniStyle;
}
/**
*
*
* @param lineAniStyle ChartAniStyle
*/
public void setLineAniStyle(int lineAniStyle) {
mLineAniStyle = lineAniStyle;
}
public void setInterpolator(Interpolator interpolator) {
mInterpolator = interpolator;
}
/**
* x
*
* @param HCoordinate
*/
public void setHCoordinate(float HCoordinate) {
mHCoordinate = mHeight - HCoordinate;
refreshExcels();
}
public int dip2px(float dipValue) {
final float scale = mContext.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
public void animateShow() {
mVa.cancel();
if (mChartStyle == ChartStyle.LINE) {
mCrosses = true;
}
mVa.start();
}
public float getAbscissaMsgSize() {
return mAbscissaMsgSize;
}
public void setAbscissaMsgSize(float abscissaMsgSize) {
mAbscissaMsgSize = abscissaMsgSize;
mAbscissaPaint.setTextSize(mAbscissaMsgSize);
}
public int getTextBgColor() {
return mTextBgColor;
}
public void setTextBgColor(int textBgColor) {
mTextBgColor = textBgColor;
mTextBgPaint.setColor(mTextBgColor);
}
public int getAbscissaMsgColor() {
return mAbscissaMsgColor;
}
/**
*
*
* @param abscissaMsgColor
*/
public void setAbscissaMsgColor(int abscissaMsgColor) {
mAbscissaMsgColor = abscissaMsgColor;
mAbscissaPaint.setColor(mAbscissaMsgColor);
}
/**
*
*
* @param colors
*/
public void setExecelPaintShaderColors(int[] colors) {
mShaderColors = colors;
}
/**
*
*
* @param scrollAble
*/
public void setScrollAble(boolean scrollAble) {
mScrollAble = scrollAble;
}
/**
* /
*
*
* @param fixedNums
*/
public void setFixedWidth(int fixedNums) {
mScrollAble = false;
mFixedNums = fixedNums;
}
public void setSelectedModed(int selectedModed) {
this.selectedModed = selectedModed;
postInvalidate();
}
public int getSelectedModed() {
return selectedModed;
}
public float getLinePointRadio() {
return mLinePointRadio;
}
/**
*
*
* @param barRadio
*/
public void setBarRadio(float barRadio) {
mBarRadio = barRadio;
}
/**
*
*
* @param linePointRadio
*/
public void setLinePointRadio(float linePointRadio) {
mLinePointRadio = linePointRadio;
}
public void setNeedLineEffict(boolean needLineEffict) {
mNeedLineEffict = needLineEffict;
}
/**
* sppx
*
* @param spValue DisplayMetricsscaledDensity
*/
public int sp2px(float spValue) {
final float fontScale = mContext.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
}
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/graph/NChart.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 9,307 |
```java
package com.jonas.jgraph.models;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.RectF;
/**
* @author yun.
* @date 2016/6/8
* @des []
* @since [path_to_url
* <p><a href="path_to_url">github</a>
*/
public class NExcel {
private float mWidth;//
private float mHeight;//y
private PointF mStart = new PointF();//
private float mMidX;// x
private int mColor;
private float mNum; //
private float mMax; //
private String textMsg; //
private String mXmsg; //
private float mUpper;
private float mLower;
/**
*
*/
private String unit;
public NExcel(float num, String mXmsg){
this(0, num, mXmsg);
}
public NExcel(float lower, float upper, String mXmsg){
this(lower, upper, mXmsg, Color.GRAY);
}
public NExcel(float lower, float upper, String mXmsg, int color){
this(lower, upper, "", mXmsg, Color.GRAY);
}
public NExcel(float num, String unit, String mXmsg){
this(0, num, unit, mXmsg, Color.GRAY);
}
public NExcel(float lower, float upper, String unit, String mXmsg, int color){
mUpper = upper;
mLower = lower;
mHeight = mNum = upper-lower;
mStart.y = mLower;
this.mXmsg = mXmsg;
this.unit = unit;
this.mColor = color;
}
public RectF getRectF(){
return new RectF(mStart.x, mStart.y-mHeight, mStart.x+mWidth, mStart.y);
}
public PointF getMidPointF(){
return new PointF(getMidX(), mStart.y-mHeight);
}
public String getTextMsg(){
return textMsg;
}
public String getUnit(){
return unit;
}
public void setUnit(String unit){
this.unit = unit;
}
public void setTextMsg(String textMsg){
this.textMsg = textMsg;
}
public float getWidth(){
return mWidth;
}
public void setWidth(float width){
this.mWidth = width;
}
public float getHeight(){
return mHeight;
}
public void setHeight(float height){
this.mHeight = height;
}
public PointF getStart(){
return mStart;
}
public void setStart(PointF start){
this.mStart = start;
}
public float getMidX(){
if(null != mStart) {
mMidX = mStart.x+mWidth/2;
}else {
throw new RuntimeException("mStart ");
}
return mMidX;
}
public void setMidX(float midX){
this.mMidX = midX;
}
public int getColor(){
return mColor;
}
public void setColor(int color){
mColor = color;
}
public float getNum(){
return mNum;
}
public void setNum(float num){
this.mNum = num;
}
public float getMax(){
return mMax;
}
public void setMax(float max){
this.mMax = max;
}
public String getXmsg(){
return mXmsg;
}
public void setXmsg(String xmsg){
this.mXmsg = xmsg;
}
public float getUpper(){
return mUpper;
}
public void setUpper(float upper){
mUpper = upper;
}
public float getLower(){
return mLower;
}
public void setLower(float lower){
mLower = lower;
}
}
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/models/NExcel.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 830 |
```java
package com.jonas.jgraph.utils;
import android.content.Context;
/**
* @author jiangzuyun.
* @date 2016/7/14
* @des []
* @since [/]
*/
public class MathHelper {
/**
* @param num
* @return num 5
*/
public static int getRound5(float num){
return ( (int)( num+2.5 ) )/5*5;
}
/**
* @param num
* @return num 5
*/
public static int getCeil5(float num){
return ( (int)( num+4.9999999 ) )/5*5;
}
/**
*
*
* @param num
* @return
*/
public static int getCeil10(float num){
return ( (int)( num+9.9999999 ) )/10*10;
}
/**
*
*
* @param num
* @return
*/
public static int getRound10(float num){
return ( (int)( num+5 ) )/10*10;
}
public static int getCast10(float num){
return ( (int)( num ) )/10*10;
}
/**
* (x1,y1)(x2,y2)
*
* @param x1
* @param y1
* @param x2
* @param y2
* @return
*/
public static double getPointAngle(float x1, float y1, float x2, float y2){
float a = x1-x2;
float b = y1-y2;
//
double c = Math.sqrt(Math.pow(a, 2)+Math.pow(b, 2));
//
double acos = Math.acos(a/c);
// =/PI * 180
double clickAngle = acos/Math.PI*180;// 0-180
if(y1<y2) {
//
clickAngle = 2*180-clickAngle;
}
return clickAngle;
}
public static int dip2px(Context context, float dipValue){
final float scale = context.getResources().getDisplayMetrics().density;
return (int)( dipValue*scale+0.5f );
}
/**
* sppx
*
* @param sp
* DisplayMetricsscaledDensity
*/
public static int sp2px(Context context, float sp){
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int)( sp*fontScale+0.5f );
}
}
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/utils/MathHelper.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 580 |
```java
package com.jonas.jgraph.utils;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.RectF;
import android.support.annotation.NonNull;
import com.jonas.jgraph.models.Jchart;
/**
* @author jiangzuyun.
* @date 2016/10/19
* @des []
* @since [/]
*/
public class CalloutHelper {
// private static Paint mCalloutBgPaint;
// private static float mLineWidth;
// private static Paint mCalloutPaint;
// private static float mWidth;
//
// public static CalloutHelper createHelper(float lineWidth, float width, Paint calloutBgPaint,Paint calloutPaint) {
// mLineWidth = lineWidth;
// mWidth = width;
// mCalloutBgPaint = calloutBgPaint;
// mCalloutPaint = calloutPaint;
// return new CalloutHelper();
// }
/**
*
*
* @param canvas
* @param excel
* @param top
*/
public static void drawCalloutActual(Canvas canvas, @NonNull Jchart excel, boolean top, float lineWidth, float width,
Paint calloutBgPaint, Paint calloutPaint,boolean scrollAble) {
// public static void drawCalloutActual(Canvas canvas, @NonNull SugChart.SugExcel excel, boolean top) {
float toPoint = dip2px(2) + lineWidth / 2;//
if (excel.getHeight() <= 0) {
return;
}
PointF midPointF = excel.getMidPointF();
// String msg = excel.getUpper() + excel.getUnit();
String msg = String.valueOf(excel.getShowMsg());
Path triangleBg = new Path();
float calloutHeight = dip2px(21);//
float bgPading = dip2px(6);//
float triangleBgWidth = dip2px(8);
float triangleBgHeight = dip2px(4);
//
if (top) {
triangleBg.moveTo(midPointF.x, midPointF.y - toPoint);
triangleBg.lineTo(midPointF.x - triangleBgWidth / 2, midPointF.y - toPoint - triangleBgHeight - 1);
triangleBg.lineTo(midPointF.x + triangleBgWidth / 2, midPointF.y - toPoint - triangleBgHeight - 1);
triangleBg.close();
} else {
triangleBg.moveTo(midPointF.x, midPointF.y + toPoint);
triangleBg.lineTo(midPointF.x - triangleBgWidth / 2, midPointF.y + toPoint + triangleBgHeight + 1);
triangleBg.lineTo(midPointF.x + triangleBgWidth / 2, midPointF.y + toPoint + triangleBgHeight + 1);
triangleBg.close();
}
canvas.drawPath(triangleBg, calloutBgPaint);
float msgWidth = calloutPaint.measureText(msg);
RectF rectF = new RectF(midPointF.x - msgWidth / 2f - bgPading, midPointF.y - toPoint - triangleBgHeight - calloutHeight
, midPointF.x + msgWidth / 2f + bgPading, midPointF.y - toPoint - triangleBgHeight);
if (!top) {
rectF.offset(0, lineWidth + getCalloutHeight() + dip2px(4) + dip2px(2));
}
float dffw = 0;
if(!scrollAble) {
//
dffw = rectF.right-width;
}
float msgX = midPointF.x;
float magin = 1;
if (dffw > 0) {
rectF.right = rectF.right - dffw - magin;
rectF.left = rectF.left - dffw - magin;
msgX = midPointF.x - dffw - magin;
} else if (rectF.left < 0) {
rectF.right = rectF.right - rectF.left + magin;
msgX = midPointF.x - rectF.left + magin;
rectF.left = magin;
}
canvas.drawRoundRect(rectF, rectF.height() / 2f, rectF.height() / 2f, calloutBgPaint);
canvas.drawText(msg, msgX, rectF.bottom - rectF.height() / 2f + getTextHeight(calloutPaint) / 2, calloutPaint);
}
public static int dip2px(float dipValue) {
final float scale = Resources.getSystem().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
public static float getTextHeight(Paint textPaint) {
return -textPaint.ascent() - textPaint.descent();
}
/**
*
* @return
*/
public static float getCalloutHeight() {
// + +
return dip2px(21) + dip2px(2) + dip2px(4);
}
}
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/utils/CalloutHelper.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 1,086 |
```java
package com.jonas.jgraph.utils;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.support.annotation.Size;
import java.security.SecureRandom;
/**
* @author yun.
* @date 2016/7/13
* @des []
* @since [path_to_url
* <p><a href="path_to_url">github</a>
*/
public class DrawHelper {
/**
* lsPointFlePointF sPointePointF
*
* @param path
* @param sPoint
* @param ePointF
* @param lsPointF
* @param lePointF
* @param aniRatio
*/
public static void AnipathCubicFromLast(Path path, PointF sPoint, PointF ePointF, PointF lsPointF, PointF lePointF, float aniRatio){
float con_x = ( sPoint.x+ePointF.x )/2;
path.cubicTo(con_x, lsPointF.y+( sPoint.y-lsPointF.y )*aniRatio, con_x,
lePointF.y+( ePointF.y-lePointF.y )*aniRatio, ePointF.x, lePointF.y+( ePointF.y-lePointF.y )*aniRatio);
}
public static void AnipathLinetoFromLast(Path path, PointF toPoint, PointF ltoPointF, float aniRatio){
path.lineTo(toPoint.x, ltoPointF.y+( toPoint.y-ltoPointF.y )*aniRatio);
}
/**
* prePointnextPointF
*
* @param pathline
* @param prePoint
* @param nextPointF
*/
public static void pathCubicTo(Path pathline, PointF prePoint, PointF nextPointF){
float c_x = ( prePoint.x+nextPointF.x )/2;
pathline.cubicTo(c_x, prePoint.y, c_x, nextPointF.y, nextPointF.x, nextPointF.y);
}
/**
*
*
* @return
*/
public int randomColor(){
SecureRandom random = new SecureRandom();
int red = random.nextInt(256);
int green = random.nextInt(256);
int blue = random.nextInt(256);
return Color.rgb(red, green, blue);
}
/**
*
*
* @param paint
*
* @return
* thanks: path_to_url
*/
public float getFontHeight(Paint paint){
return paint.ascent()+paint.descent();
// Paint.FontMetrics fm = paint.getFontMetrics();
// return (float)Math.ceil(fm.descent-fm.ascent);
}
/**
*
*
* @param paint
*
* @param str
*
* @return
*/
public float getTextWidth(Paint paint, @Size(min = 1) String str){
return paint.measureText(str, 0, str.length());
}
}
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/utils/DrawHelper.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 631 |
```java
package com.jonas.jgraph;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="path_to_url">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception{
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.jonas.jgraph.test", appContext.getPackageName());
}
}
``` | /content/code_sandbox/jgraph/src/androidTest/java/com/jonas/jgraph/ExampleInstrumentedTest.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 145 |
```java
package com.jonas.schart;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
``` | /content/code_sandbox/app/src/test/java/com/jonas/schart/ExampleUnitTest.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 72 |
```java
package com.jonas.jgraph.utils;
/*
* File Name: MyFlowLayout.java
* History:
* Created by mwqi on 2014-4-18
*/
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Refuse
*
*/
public class FlowLayout extends ViewGroup {
public static final int DEFAULT_SPACING = 20;
/** */
private int mHorizontalSpacing = DEFAULT_SPACING;
/** */
private int mVerticalSpacing = DEFAULT_SPACING;
/** */
boolean mNeedLayout = true;
/** View */
private int mUsedWidth = 0;
/** */
private final List<Line> mLines = new ArrayList<Line>();
private Line mLine = null;
/** */
private int mMaxLinesCount = Integer.MAX_VALUE;
public FlowLayout(Context context) {
super(context);
}
public FlowLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public void setHorizontalSpacing(int spacing) {
if (mHorizontalSpacing != spacing) {
mHorizontalSpacing = spacing;
requestLayoutInner();
}
}
public void setVerticalSpacing(int spacing) {
if (mVerticalSpacing != spacing) {
mVerticalSpacing = spacing;
requestLayoutInner();
}
}
public void setMaxLines(int count) {
if (mMaxLinesCount != count) {
mMaxLinesCount = count;
requestLayoutInner();
}
}
private void requestLayoutInner() {
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec)
- getPaddingRight() - getPaddingLeft();
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec)
- getPaddingTop() - getPaddingBottom();
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
restoreLine();//
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(sizeWidth,
modeWidth == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST
: modeWidth);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
sizeHeight,
modeHeight == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST
: modeHeight);
// child
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
if (mLine == null) {
mLine = new Line();
}
int childWidth = child.getMeasuredWidth();
mUsedWidth += childWidth;//
if (mUsedWidth <= sizeWidth) {// child
mLine.addView(child);// child
mUsedWidth += mHorizontalSpacing;//
if (mUsedWidth >= sizeWidth) {//
if (!newLine()) {
break;
}
}
} else {//
if (mLine.getViewCount() == 0) {// childchild
mLine.addView(child);// child
if (!newLine()) {//
break;
}
} else {//
if (!newLine()) {//
break;
}
// childchild
mLine.addView(child);
mUsedWidth += childWidth + mHorizontalSpacing;
}
}
}
if (mLine != null && mLine.getViewCount() > 0
&& !mLines.contains(mLine)) {
//
mLines.add(mLine);
}
int totalWidth = MeasureSpec.getSize(widthMeasureSpec);
int totalHeight = 0;
final int linesCount = mLines.size();
for (int i = 0; i < linesCount; i++) {//
totalHeight += mLines.get(i).mHeight;
}
totalHeight += mVerticalSpacing * (linesCount - 1);//
totalHeight += getPaddingTop() + getPaddingBottom();// padding
// viewview
// Viewview
setMeasuredDimension(totalWidth,
resolveSize(totalHeight, heightMeasureSpec));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (!mNeedLayout || changed) {//
mNeedLayout = false;
int left = getPaddingLeft();//
int top = getPaddingTop();
final int linesCount = mLines.size();
for (int i = 0; i < linesCount; i++) {
final Line oneLine = mLines.get(i);
oneLine.layoutView(left, top);//
top += oneLine.mHeight + mVerticalSpacing;// top
}
}
}
/** */
private void restoreLine() {
mLines.clear();
mLine = new Line();
mUsedWidth = 0;
}
/** */
private boolean newLine() {
mLines.add(mLine);
if (mLines.size() < mMaxLinesCount) {
mLine = new Line();
mUsedWidth = 0;
return true;
}
return false;
}
// ==========================================================================
// Inner/Nested Classes
// ==========================================================================
/**
* ViewView
*/
class Line {
int mWidth = 0;// View
int mHeight = 0;// ViewView
List<View> views = new ArrayList<View>();
public void addView(View view) {//
views.add(view);
mWidth += view.getMeasuredWidth();
int childHeight = view.getMeasuredHeight();
mHeight = mHeight < childHeight ? childHeight : mHeight;// View
}
public int getViewCount() {
return views.size();
}
public void layoutView(int l, int t) {//
int left = l;
int top = t;
int count = getViewCount();
//
int layoutWidth = getMeasuredWidth() - getPaddingLeft()
- getPaddingRight();
// View
int surplusWidth = layoutWidth - mWidth - mHorizontalSpacing
* (count - 1);
if (surplusWidth >= 0) {//
// floatint
int splitSpacing = (int) (surplusWidth / count + 0.5);
for (int i = 0; i < count; i++) {
final View view = views.get(i);
int childWidth = view.getMeasuredWidth();
int childHeight = view.getMeasuredHeight();
// ViewViewView2
int topOffset = (int) ((mHeight - childHeight) / 2.0 + 0.5);
if (topOffset < 0) {
topOffset = 0;
}
// View
childWidth = childWidth + splitSpacing;
view.getLayoutParams().width = childWidth;
if (splitSpacing > 0) {// Viewmeasure
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(
childWidth, MeasureSpec.EXACTLY);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(
childHeight, MeasureSpec.EXACTLY);
view.measure(widthMeasureSpec, heightMeasureSpec);
}
// View
view.layout(left, top + topOffset, left + childWidth, top
+ topOffset + childHeight);
left += childWidth + mHorizontalSpacing; // Viewleft
}
} else {
if (count == 1) {
View view = views.get(0);
view.layout(left, top, left + view.getMeasuredWidth(), top
+ view.getMeasuredHeight());
} else {
//
}
}
}
}
public List getCheckedId() {
List<Integer> checkedid = new ArrayList<>();
for (int i = 0; i < getChildCount(); i++) {
View childAt = getChildAt(i);
if (childAt instanceof CheckBox) {
if (((CheckBox)childAt).isChecked()) {
checkedid.add(i);
}
}
}
return checkedid;
}
}
``` | /content/code_sandbox/jgraph/src/main/java/com/jonas/jgraph/utils/FlowLayout.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 1,812 |
```java
package com.jonas.schart;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
public class EntActivity extends ListActivity {
String[] items = new String[]{"NChart", "ChartActivity"};
Class[] clazz = new Class[]{MainActivity.class, ChartActivity.class};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(position);
}
});
}
private void startActivity(int position) {
Intent intent = new Intent(this, clazz[position]);
startActivity(intent);
}
}
``` | /content/code_sandbox/app/src/main/java/com/jonas/schart/EntActivity.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 184 |
```java
package com.jonas.schart;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.SeekBar;
import com.jonas.jgraph.graph.NChart;
import com.jonas.jgraph.models.NExcel;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private SeekBar mSbBarwidth;
private SeekBar mSbBarinterval;
private SeekBar mSbHcoordinate;
private NChart mChart;
private boolean style_bar = true;
private SeekBar mSbmabove;
private void assignViews(){
mSbBarwidth = (SeekBar)findViewById(R.id.sb_barwidth);
mSbBarinterval = (SeekBar)findViewById(R.id.sb_barinterval);
mSbHcoordinate = (SeekBar)findViewById(R.id.sb_hcoordinate);
mSbmabove = (SeekBar)findViewById(R.id.sb_mabove);
}
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mChart = (NChart)findViewById(R.id.sug_recode_schar);
List<NExcel> nExcelList = new ArrayList<>();
Random random = new Random();
for(int i = 0; i<8; i++) {
nExcelList.add(new NExcel(80+random.nextInt(100), ""));
}
nExcelList.add(new NExcel(99, 150, ""));
// Color.parseColor("#ffe9d1ba");
// mChart.setScrollAble(false);
// mChart.setFixedWidth(30);
mChart.setBarStanded(7);
// mChart.setExecelPaintShaderColors(new int[]{Color.parseColor("#089900"), Color.parseColor("#9FC700")});
// mChart.setExecelPaintShaderColors(new int[]{Color.parseColor("#4df1dbd4"), Color.TRANSPARENT});
mChart.setNormalColor(Color.parseColor("#089900"));
mChart.cmdFill(nExcelList);
assignViews();
setListeners();
}
private void setListeners(){
mSbBarwidth.setOnSeekBarChangeListener(this);
mSbBarwidth.setProgress((int)mChart.getBarWidth());
mSbBarinterval.setOnSeekBarChangeListener(this);
mSbBarinterval.setProgress((int)mChart.getInterval());
mSbHcoordinate.setOnSeekBarChangeListener(this);
mSbHcoordinate.setProgress((int)mChart.getHCoordinate());
mSbmabove.setOnSeekBarChangeListener(this);
mSbmabove.setProgress((int)mChart.getAbove());
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
switch(seekBar.getId()) {
case R.id.sb_barwidth:
mChart.setBarWidth(progress);
break;
case R.id.sb_barinterval:
mChart.setInterval(progress);
break;
case R.id.sb_hcoordinate:
mChart.setHCoordinate(progress);
break;
case R.id.sb_mabove:
mChart.setAbove(progress);
break;
}
mChart.postInvalidate();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar){
}
@Override
public void onStopTrackingTouch(SeekBar seekBar){
}
public void stylechange(View v){
mChart.setChartStyle(( style_bar = !style_bar ) ? NChart.ChartStyle.BAR : NChart.ChartStyle.LINE);
mChart.postInvalidate();
}
public void animate(View v){
mChart.animateShow();
}
public void selecterChange(View v){
if (mChart.getSelectedModed()== NChart.SelectedMode.selecetdMsgShow) {
mChart.setSelectedModed(NChart.SelectedMode.selectedActivated);
} else {
mChart.setSelectedModed(NChart.SelectedMode.selecetdMsgShow);
}
}
}
``` | /content/code_sandbox/app/src/main/java/com/jonas/schart/MainActivity.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 830 |
```java
package com.jonas.schart;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ListView;
import com.jonas.jgraph.graph.JcoolGraph;
import com.jonas.jgraph.models.Jchart;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import static com.jonas.jgraph.graph.JcoolGraph.LINE_DASH_0;
import static com.jonas.jgraph.inter.BaseGraph.SELECETD_MSG_SHOW_TOP;
import static com.jonas.jgraph.inter.BaseGraph.SELECETD_NULL;
public class ChartActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private JcoolGraph mLineChar;
private String linestyleItems[] = new String[]{"", ""};
private String showstyleItems[] = new String[]{"DRAWING", "SECTION", "FROMLINE", "FROMCORNER", "ASWAVE"};
private String barshowstyleItems[] = new String[]{"ASWAVE", "FROMLINE", "EXPAND", "SECTION"};
private int chartNum = 14;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chart);
setUpListview();
setupCheckBox();
mLineChar = (JcoolGraph)findViewById(R.id.sug_recode_line);
List<Jchart> lines = new ArrayList<>();
for(int i = 0; i<chartNum; i++) {
lines.add(new Jchart(new SecureRandom().nextInt(50)+15, Color.parseColor("#5F77F6")));
// lines.add(new Jchart(10,new SecureRandom().nextInt(50) + 15,"test", Color.parseColor("#b8e986")));
}
// for(Jchart line : lines) {
// line.setStandedHeight(100);
// }
// lines.get(new SecureRandom().nextInt(chartNum-1)).setUpper(0);
lines.get(1).setUpper(0);
lines.get(new SecureRandom().nextInt(chartNum-1)).setLower(10);
lines.get(chartNum-2).setUpper(0);
// mLineChar.setScrollAble(true);
// mLineChar.setLineMode();
mLineChar.setLinePointRadio((int)mLineChar.getLineWidth());
// mLineChar.setLineMode(JcoolGraph.LineMode.LINE_DASH_0);
// mLineChar.setLineStyle(JcoolGraph.LineStyle.LINE_BROKEN);
// mLineChar.setYaxisValues("test","","text");
// mLineChar.setSelectedMode(BaseGraph.SelectedMode.SELECETD_MSG_SHOW_TOP);
mLineChar.setNormalColor(Color.parseColor("#676567"));
mLineChar.feedData(lines);
( (FrameLayout)mLineChar.getParent() ).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
mLineChar.postInvalidate();
}
});
}
private void setupCheckBox(){
( (CheckBox)findViewById(R.id.graphshader) ).setOnCheckedChangeListener(this);
( (CheckBox)findViewById(R.id.areashader) ).setOnCheckedChangeListener(this);
( (CheckBox)findViewById(R.id.skep0) ).setOnCheckedChangeListener(this);
( (CheckBox)findViewById(R.id.select) ).setOnCheckedChangeListener(this);
( (CheckBox)findViewById(R.id.scrollable) ).setOnCheckedChangeListener(this);
( (CheckBox)findViewById(R.id.ymsg) ).setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
switch(buttonView.getId()) {
case R.id.ymsg:
if(isChecked) {
mLineChar.setYaxisValues(20, 80, 3);
}else {
mLineChar.setYaxisValues(0, 0, 0);
}
break;
case R.id.scrollable:
if(isChecked) {
mLineChar.setScrollAble(true);
mLineChar.setVisibleNums(10);
}else {
mLineChar.setScrollAble(false);
}
break;
case R.id.skep0:
if(isChecked) {
mLineChar.setLineMode(LINE_DASH_0);
}else {
mLineChar.setLineMode(JcoolGraph.LINE_JUMP0);
}
break;
case R.id.select:
if(isChecked) {
mLineChar.setSelectedMode(SELECETD_MSG_SHOW_TOP);
}else {
mLineChar.setSelectedMode(SELECETD_NULL);
}
break;
case R.id.graphshader:
if(isChecked) {
mLineChar.setPaintShaderColors(Color.RED, Color.parseColor("#E79D23"),
Color.parseColor("#FFF03D"), Color.parseColor("#A9E16F"), Color.parseColor("#75B9EF"));
}else {
mLineChar.setPaintShaderColors(null);
}
break;
case R.id.areashader:
if(isChecked) {
mLineChar.setShaderAreaColors(Color.parseColor("#4B494B"), Color.TRANSPARENT);
}else {
mLineChar.setShaderAreaColors(null);
}
}
mLineChar.postInvalidate();
}
private void setUpListview(){
ListView graphstyle = (ListView)findViewById(R.id.graphstyle);
final ListView linestyle = (ListView)findViewById(R.id.linestyle);
final ListView showstyle = (ListView)findViewById(R.id.showstyle);
linestyle.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
showstyle.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
graphstyle.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
ArrayAdapter graphstyleadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice,
new String[]{"", ""});
ArrayAdapter linestyleadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice,
linestyleItems);
ArrayAdapter showstyleadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice,
showstyleItems);
graphstyle.setAdapter(graphstyleadapter);
linestyle.setAdapter(linestyleadapter);
showstyle.setAdapter(showstyleadapter);
graphstyle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
mLineChar.setGraphStyle(position);
mLineChar.invalidate();
ArrayAdapter linestyleadapter;
if(position == 1) {
linestyle.setVisibility(View.VISIBLE);
linestyleadapter = new ArrayAdapter<String>(ChartActivity.this,
android.R.layout.simple_list_item_single_choice, showstyleItems);
}else {
linestyle.setVisibility(View.GONE);
linestyleadapter = new ArrayAdapter<String>(ChartActivity.this,
android.R.layout.simple_list_item_single_choice, barshowstyleItems);
}
showstyle.setAdapter(linestyleadapter);
}
});
linestyle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
mLineChar.setLineStyle(position);
mLineChar.invalidate();
}
});
showstyle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
if(linestyle.getVisibility() == View.GONE) {
mLineChar.setBarShowStyle(position);
}else {
mLineChar.setLineShowStyle(position);
}
}
});
}
public void clicked(View v){
mLineChar.aniShow_growing();
}
public void changedata(View v){
new Thread(new Runnable() {
@Override
public void run(){
final List<Jchart> lines = new ArrayList<>();
for(int i = 0; i<chartNum; i++) {
int num = new SecureRandom().nextInt(150)+15;
lines.add(new Jchart(new SecureRandom().nextInt(30), num, 0xb8e986));
}
mLineChar.post(new Runnable() {
@Override
public void run(){
mLineChar.aniChangeData(lines);
}
});
}
}).start();
}
}
``` | /content/code_sandbox/app/src/main/java/com/jonas/schart/ChartActivity.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 1,736 |
```java
package com.jonas.schart;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="path_to_url">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
``` | /content/code_sandbox/app/src/androidTest/java/com/jonas/schart/ApplicationTest.java | java | 2016-05-07T12:57:27 | 2024-08-03T07:47:51 | Jgraph | 5hmlA/Jgraph | 1,290 | 60 |
```java
package easymvp.weaver;
import javax.inject.Inject;
import javax.inject.Provider;
import easymvp.annotation.Presenter;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LineNumberAttribute;
import javassist.expr.ExprEditor;
import javassist.expr.FieldAccess;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
class Dagger2Extension {
private final ClassPool pool;
private final ViewDelegateBinder viewDelegateBinder;
Dagger2Extension(ViewDelegateBinder viewDelegateBinder, ClassPool pool) {
this.viewDelegateBinder = viewDelegateBinder;
this.pool = pool;
}
boolean apply(CtClass candidateClass)
throws CannotCompileException, NotFoundException {
CtField presenterField = null;
for (CtField ctField : candidateClass.getDeclaredFields()) {
if (ctField.hasAnnotation(Inject.class) && ctField.hasAnnotation(Presenter.class)) {
presenterField = ctField;
break;
}
}
if (presenterField == null) {
return false;
}
CtClass membersInjectorClass = pool.get(
candidateClass.getPackageName() + "." + candidateClass.getSimpleName() + "_MembersInjector");
CtField presenterFieldInInjector = null;
for (CtField field : membersInjectorClass.getDeclaredFields()) {
if (field.getName().equals(presenterField.getName() + "Provider")) {
presenterFieldInInjector = field;
break;
}
}
if (presenterFieldInInjector == null) {
return false;
}
viewDelegateBinder.log("DaggerExtension", "MembersInjector class has been found for " +
candidateClass.getSimpleName());
addPresenterProviderField(candidateClass, presenterFieldInInjector);
replacePresenterWithPresenterProvider(membersInjectorClass, presenterField.getName(),
presenterFieldInInjector.getName());
return true;
}
private void addPresenterProviderField(CtClass candidateClass, CtField presenterFieldInInjector)
throws CannotCompileException {
CtField presenterProvider =
CtField.make(Provider.class.getName() + " $$presenterProvider = null;", candidateClass);
presenterProvider.setGenericSignature(presenterFieldInInjector.getGenericSignature());
candidateClass.addField(presenterProvider);
}
private void replacePresenterWithPresenterProvider(CtClass membersInjectorClass,
final String presenterFieldName,
final String presenterProviderField)
throws NotFoundException, CannotCompileException {
CtMethod injectMembers = membersInjectorClass.getDeclaredMethod("injectMembers");
final int[] injectedPresenterLineNumber = {-1};
injectMembers.instrument(new ExprEditor() {
@Override
public void edit(FieldAccess f) throws CannotCompileException {
if (f.isWriter() && f.getFieldName().equals(presenterFieldName)) {
injectedPresenterLineNumber[0] = f.getLineNumber();
}
}
});
if (injectedPresenterLineNumber[0] != -1) {
deleteLine(injectMembers, injectedPresenterLineNumber[0]);
fillPresenterProviderInView(injectMembers, presenterProviderField, injectedPresenterLineNumber[0]);
viewDelegateBinder.log("DaggerExtension",
"Remove presenter injection from " +
membersInjectorClass.getSimpleName() +
" and replace with our presenterProvider ");
viewDelegateBinder.writeClass(membersInjectorClass);
}
}
private void deleteLine(CtMethod method, int lineNumberToReplace) {
CodeAttribute codeAttribute = method.getMethodInfo().getCodeAttribute();
LineNumberAttribute
lineNumberAttribute = (LineNumberAttribute) codeAttribute.getAttribute(LineNumberAttribute.tag);
int startPc = lineNumberAttribute.toStartPc(lineNumberToReplace);
int endPc = lineNumberAttribute.toStartPc(lineNumberToReplace + 1);
byte[] code = codeAttribute.getCode();
for (int i = startPc; i < endPc; i++) {
code[i] = CodeAttribute.NOP;
}
}
private void fillPresenterProviderInView(CtMethod method, String fieldToUse, int lineNumber)
throws CannotCompileException {
method.insertAt(lineNumber, "$1.$$presenterProvider = " + fieldToUse + ";");
}
}
``` | /content/code_sandbox/easymvp-weaver/src/main/java/easymvp/weaver/Dagger2Extension.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 910 |
```java
package easymvp.weaver;
import java.util.List;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
final class JavassistUtils {
static CtClass[] stringToCtClass(ClassPool pool, String[] params)
throws NotFoundException {
CtClass[] ctClasses = new CtClass[params.length];
for (int i = 0; i < params.length; i++) {
ctClasses[i] = pool.get(params[i]);
}
return ctClasses;
}
static String[] ctClassToString(CtClass[] params) {
String[] strings = new String[params.length];
for (int i = 0; i < params.length; i++) {
strings[i] = params[i].getName();
}
return strings;
}
static boolean sameSignature(List<String> parameters, CtMethod method)
throws NotFoundException {
CtClass[] methodParameters = method.getParameterTypes();
if (methodParameters.length == 0 && parameters.size() == 0) return true;
if (methodParameters.length != 0 && parameters.size() == 0) return false;
if (methodParameters.length == 0 && parameters.size() != 0) return false;
for (CtClass clazz : method.getParameterTypes()) {
if (!parameters.contains(clazz.getName())) return false;
}
return true;
}
}
``` | /content/code_sandbox/easymvp-weaver/src/main/java/easymvp/weaver/JavassistUtils.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 320 |
```java
package easymvp;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;
/**
* A base class for implementing a {@link Presenter} with RxJava functionality.
*
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public abstract class RxPresenter<V> extends AbstractPresenter<V> {
private CompositeSubscription subscriptions = new CompositeSubscription();
@Override
public void onDestroyed() {
super.onDestroyed();
subscriptions.unsubscribe();
}
public void addSubscription(Subscription subscription) {
subscriptions.add(subscription);
}
public void removeSubscription(Subscription subscription) {
subscriptions.remove(subscription);
}
}
``` | /content/code_sandbox/easymvp-rx-api/src/main/java/easymvp/RxPresenter.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 138 |
```java
package easymvp.usecase;
import javax.annotation.Nullable;
import easymvp.executer.PostExecutionThread;
import easymvp.executer.UseCaseExecutor;
import rx.Completable;
/**
* Reactive version of a {@link UseCase}.
* <p>
* It's useful for use-cases without any response value.
*
* @param <Q> The request value.
* @author Saeed Masoumi (saeed@6thsolution.com)
* @see Completable
*/
public abstract class CompletableUseCase<Q> extends UseCase<Completable, Q> {
private final Completable.Transformer schedulersTransformer;
public CompletableUseCase(final UseCaseExecutor useCaseExecutor,
final PostExecutionThread postExecutionThread) {
super(useCaseExecutor, postExecutionThread);
schedulersTransformer = new Completable.Transformer() {
@Override
public Completable call(Completable completable) {
return completable.subscribeOn(useCaseExecutor.getScheduler())
.observeOn(postExecutionThread.getScheduler());
}
};
}
@Override
public Completable execute(@Nullable Q param) {
return interact(param).compose(getSchedulersTransformer());
}
private Completable.Transformer getSchedulersTransformer() {
return schedulersTransformer;
}
}
``` | /content/code_sandbox/easymvp-rx-api/src/main/java/easymvp/usecase/CompletableUseCase.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 270 |
```java
package easymvp.usecase;
import javax.annotation.Nullable;
import easymvp.executer.PostExecutionThread;
import easymvp.executer.UseCaseExecutor;
import rx.Scheduler;
/**
* Each {@code UseCase} of the system orchestrate the flow of data to and from the entities.
* <p>
* Outer layers of system can execute use cases by calling {@link #execute(Object)}} method. Also
* you can use {@link #useCaseExecutor} to execute the job in a background thread and {@link
* #postExecutionThread} to post the result to another thread(usually UI thread).
*
* @param <P> The response type of a use case.
* @param <Q> The request type of a use case.
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public abstract class UseCase<P, Q> {
private final UseCaseExecutor useCaseExecutor;
private final PostExecutionThread postExecutionThread;
public UseCase(UseCaseExecutor useCaseExecutor,
PostExecutionThread postExecutionThread) {
this.useCaseExecutor = useCaseExecutor;
this.postExecutionThread = postExecutionThread;
}
/**
* Executes use case. It should call {@link #interact(Object)} to get response value.
*/
public abstract P execute(@Nullable Q param);
/**
* A hook for interacting with the given parameter(request value) and returning a response value for
* each concrete implementation.
* <p>
* It should be called inside {@link #execute(Object)}.
*
* @param param The request value.
* @return Returns the response value.
*/
protected abstract P interact(@Nullable Q param);
public Scheduler getUseCaseExecutor() {
return useCaseExecutor.getScheduler();
}
public Scheduler getPostExecutionThread() {
return postExecutionThread.getScheduler();
}
}
``` | /content/code_sandbox/easymvp-rx-api/src/main/java/easymvp/usecase/UseCase.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 402 |
```java
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*
*/
package easymvp.weaver;
import easymvp.annotation.ActivityView;
import easymvp.annotation.CustomView;
import easymvp.annotation.FragmentView;
import easymvp.annotation.conductor.ConductorController;
import java.util.Arrays;
import java.util.Set;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import weaver.common.WeaveEnvironment;
import weaver.instrumentation.injection.ClassInjector;
import weaver.processor.WeaverProcessor;
import static easymvp.weaver.JavassistUtils.ctClassToString;
import static easymvp.weaver.JavassistUtils.sameSignature;
import static easymvp.weaver.JavassistUtils.stringToCtClass;
/**
* Bytecode weaver processor.
* <p>
* After generating <code>ViewDelegate</code> classes, this processor will run and do these things:
* <ol>
* <li>Finds all classes that annotated with {@link ActivityView} ,{@link FragmentView} and {@link
* CustomView}.</li>
* <li>For each view, Adds a field correspond to his generated <code>ViewDelegate</code>
* class.</li>
* <li>Invokes all methods from injected field in the right place of view lifecycle.</li>
* </ol>
*
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public class ViewDelegateBinder extends WeaverProcessor {
private static final String FIELD_VIEW_DELEGATE = "$$viewDelegate";
private static final String FIELD_PRESENTER_PROVIDER = "$$presenterProvider";
private static final String BUNDLE_CLASS = "android.os.Bundle";
private static final String LAYOUT_INFLATER_CLASS = "android.view.LayoutInflater";
private static final String VIEW_GROUP_CLASS = "android.view.ViewGroup";
private static final String VIEW_CLASS = "android.view.View";
private static final String POINT_CUT = "org.aspectj.lang.JoinPoint";
private static final String STATEMENT_CALL_INITIALIZE =
"$s." + FIELD_VIEW_DELEGATE + ".initialize($s);";
private static final String STATEMENT_CALL_INITIALIZE_WITH_FACTORY =
"$s." + FIELD_VIEW_DELEGATE + ".initialize($s, $s." + FIELD_PRESENTER_PROVIDER + ");";
private static final String STATEMENT_CALL_ATTACH =
"$s." + FIELD_VIEW_DELEGATE + ".attachView($s);";
private static final String STATEMENT_CALL_DETACH =
"$s." + FIELD_VIEW_DELEGATE + ".detachView();";
private static final String STATEMENT_CALL_DESTROY =
"$s." + FIELD_VIEW_DELEGATE + ".destroy($s);";
private static final String ASPECTJ_GEN_METHOD = "_aroundBody";
private ClassPool pool;
private Dagger2Extension dagger2Extension;
@Override
public synchronized void init(WeaveEnvironment env) {
super.init(env);
pool = env.getClassPool();
dagger2Extension = new Dagger2Extension(this, pool);
}
@Override
public void transform(Set<? extends CtClass> candidateClasses) throws Exception {
log("Starting EasyMVP-Binder");
for (CtClass ctClass : candidateClasses) {
if (ctClass.hasAnnotation(ActivityView.class)) {
log("Start weaving " + ctClass.getSimpleName());
ClassInjector classInjector = instrumentation.startWeaving(ctClass);
injectDelegateField(ctClass, classInjector);
injectDelegateLifeCycleIntoActivity(ctClass, classInjector);
writeClass(ctClass);
} else if (ctClass.hasAnnotation(FragmentView.class)) {
log("Start weaving " + ctClass.getSimpleName());
ClassInjector classInjector = instrumentation.startWeaving(ctClass);
injectDelegateField(ctClass, classInjector);
injectDelegateLifeCycleIntoFragment(ctClass, classInjector);
writeClass(ctClass);
} else if (ctClass.hasAnnotation(CustomView.class)) {
log("Start weaving " + ctClass.getSimpleName());
ClassInjector classInjector = instrumentation.startWeaving(ctClass);
injectDelegateField(ctClass, classInjector);
injectDelegateLifeCycleIntoCustomView(ctClass, classInjector);
writeClass(ctClass);
} else if (ctClass.hasAnnotation(ConductorController.class)) {
log("Start weaving " + ctClass.getSimpleName());
ClassInjector classInjector = instrumentation.startWeaving(ctClass);
injectDelegateField(ctClass, classInjector);
injectDelegateLifeCycleIntoConductorController(ctClass, classInjector);
writeClass(ctClass);
}
}
}
@Override
public String getName() {
return "EasyMVP";
}
private void injectDelegateField(CtClass ctClass, ClassInjector classInjector)
throws Exception {
String viewClassName = ctClass.getName();
String delegateClassName = viewClassName + "_ViewDelegate";
insertDelegateField(classInjector, delegateClassName);
}
private void injectDelegateLifeCycleIntoActivity(CtClass ctClass, ClassInjector classInjector)
throws Exception {
CtMethod onCreate = findBestMethod(ctClass, "onCreate", BUNDLE_CLASS);
CtMethod onStart = findBestMethod(ctClass, "onStart");
CtMethod onStop = findBestMethod(ctClass, "onStop");
boolean applied = dagger2Extension.apply(ctClass);
AfterSuper(classInjector, onCreate,
applied ? STATEMENT_CALL_INITIALIZE_WITH_FACTORY : STATEMENT_CALL_INITIALIZE);
AfterSuper(classInjector, onStart, STATEMENT_CALL_ATTACH);
beforeSuper(classInjector, onStop, STATEMENT_CALL_DETACH);
}
private void injectDelegateLifeCycleIntoFragment(CtClass ctClass, ClassInjector classInjector)
throws Exception {
CtMethod onActivityCreated = findBestMethod(ctClass, "onActivityCreated", BUNDLE_CLASS);
CtMethod onResume = findBestMethod(ctClass, "onResume");
CtMethod onPause = findBestMethod(ctClass, "onPause");
boolean applied = dagger2Extension.apply(ctClass);
AfterSuper(classInjector, onActivityCreated,
applied ? STATEMENT_CALL_INITIALIZE_WITH_FACTORY : STATEMENT_CALL_INITIALIZE);
AfterSuper(classInjector, onResume, STATEMENT_CALL_ATTACH);
beforeSuper(classInjector, onPause, STATEMENT_CALL_DETACH);
}
private void injectDelegateLifeCycleIntoCustomView(CtClass ctClass, ClassInjector classInjector)
throws Exception {
CtMethod onAttachedToWindow = findBestMethod(ctClass, "onAttachedToWindow");
CtMethod onDetachedFromWindow = findBestMethod(ctClass, "onDetachedFromWindow");
boolean applied = dagger2Extension.apply(ctClass);
AfterSuper(classInjector, onAttachedToWindow, STATEMENT_CALL_ATTACH);
AfterSuper(classInjector, onAttachedToWindow,
applied ? STATEMENT_CALL_INITIALIZE_WITH_FACTORY : STATEMENT_CALL_INITIALIZE);
// afterSuperWithReturnType(classInjector, onDetachedFromWindow, STATEMENT_CALL_DETACH);
}
private void injectDelegateLifeCycleIntoConductorController(CtClass ctClass,
ClassInjector classInjector) throws Exception {
CtMethod onCreateView =
findBestMethod(ctClass, "onCreateView", LAYOUT_INFLATER_CLASS, VIEW_GROUP_CLASS);
CtMethod onAttach = findBestMethod(ctClass, "onAttach", VIEW_CLASS);
CtMethod onDetach = findBestMethod(ctClass, "onDetach", VIEW_CLASS);
CtMethod onDestroy = findBestMethod(ctClass, "onDestroy");
boolean applied = dagger2Extension.apply(ctClass);
afterSuperWithReturnType(classInjector, onCreateView,
applied ? STATEMENT_CALL_INITIALIZE_WITH_FACTORY : STATEMENT_CALL_INITIALIZE, true);
AfterSuper(classInjector, onAttach, STATEMENT_CALL_ATTACH);
beforeSuper(classInjector, onDetach, STATEMENT_CALL_DETACH);
beforeSuper(classInjector, onDestroy, STATEMENT_CALL_DESTROY);
}
/**
* It is possible that aspectj already manipulated this method, so in this case we should inject
* our code into {@code methodName_aroundBodyX()} which X is the lowest number of all similar
* methods to {@code methodName_aroundBody}.
*/
private CtMethod findBestMethod(CtClass ctClass, String methodName, String... params)
throws NotFoundException {
CtMethod baseMethod = null;
try {
baseMethod = ctClass.getDeclaredMethod(methodName, stringToCtClass(pool, params));
} catch (NotFoundException e) {
for (CtMethod ctMethod : ctClass.getMethods()) {
if (ctMethod.getName().equals(methodName) && sameSignature(Arrays.asList(params),
ctMethod)) {
baseMethod = ctMethod;
break;
}
}
}
CtMethod bestAspectJMethod = null;
for (CtMethod candidate : ctClass.getDeclaredMethods()) {
//aspectj is already manipulated this class
if (isAnAspectJMethod(baseMethod, candidate)) {
bestAspectJMethod = getLowerNumberOfAspectJMethods(bestAspectJMethod, candidate);
}
}
CtMethod bestMethod = bestAspectJMethod != null ? bestAspectJMethod : baseMethod;
if (bestMethod != null) {
log("Best method for " + methodName + " is: [" + bestMethod.getName() + "]");
}
return bestMethod;
}
private boolean isAnAspectJMethod(CtMethod baseMethod, CtMethod aspectMethodCandidate)
throws NotFoundException {
if (aspectMethodCandidate.getName().contains(baseMethod.getName() + ASPECTJ_GEN_METHOD)) {
//first and last parameter of _aroundBody are baseView and PointCut, so we will ignore them
boolean areSame = false;
CtClass[] baseMethodParams = baseMethod.getParameterTypes();
CtClass[] aspectMethodParams = aspectMethodCandidate.getParameterTypes();
if (baseMethodParams.length == 0 && aspectMethodParams.length == 2) {
return true;
}
if (aspectMethodParams.length - baseMethodParams.length > 2) {
return false;
}
for (int i = 1; i < aspectMethodParams.length - 1; i++) {
areSame = baseMethodParams[i - 1].getName().equals(aspectMethodParams[i].getName());
}
return areSame;
}
return false;
}
private CtMethod getLowerNumberOfAspectJMethods(CtMethod best, CtMethod candidate) {
if (best == null) {
return candidate;
}
int bestNum = getAspectJMethodNumber(best.getName());
int candidateNum = getAspectJMethodNumber(candidate.getName());
return bestNum < candidateNum ? best : candidate;
}
private int getAspectJMethodNumber(String methodName) {
String num = methodName.substring(
methodName.indexOf(ASPECTJ_GEN_METHOD) + ASPECTJ_GEN_METHOD.length());
return Integer.valueOf(num);
}
private void AfterSuper(ClassInjector classInjector, CtMethod method, String statement)
throws Exception {
if (method.getName().contains(ASPECTJ_GEN_METHOD)) {
statement = statement.replaceAll("\\$s", "\\ajc\\$this");
String methodName =
method.getName().substring(0, method.getName().indexOf(ASPECTJ_GEN_METHOD));
classInjector.insertMethod(method.getName(),
ctClassToString(method.getParameterTypes()))
.ifExists()
.afterACallTo(methodName, statement)
.inject()
.inject();
} else {
statement = statement.replaceAll("\\$s", "this");
classInjector.insertMethod(method.getName(),
ctClassToString(method.getParameterTypes()))
.ifExistsButNotOverride()
.override("{" + "super." + method.getName() + "($$);" + statement + "}")
.inject()
.ifExists()
.afterSuper(statement)
.inject()
.inject();
}
}
private void beforeSuper(ClassInjector classInjector, CtMethod method, String statement)
throws Exception {
if (method.getName().contains(ASPECTJ_GEN_METHOD)) {
statement = statement.replaceAll("\\$s", "\\ajc\\$this");
String methodName =
method.getName().substring(0, method.getName().indexOf(ASPECTJ_GEN_METHOD));
classInjector.insertMethod(method.getName(),
ctClassToString(method.getParameterTypes()))
.ifExists()
.beforeACallTo(methodName, statement)
.inject()
.inject();
} else {
statement = statement.replaceAll("\\$s", "this");
classInjector.insertMethod(method.getName(),
ctClassToString(method.getParameterTypes()))
.ifExistsButNotOverride()
.override("{" + statement + "super." + method.getName() + "($$);" + "}")
.inject()
.ifExists()
.beforeSuper(statement)
.inject()
.inject();
}
}
private void afterSuperWithReturnType(ClassInjector classInjector, CtMethod method,
String statement, boolean returnSuperClass) throws Exception {
if (method.getName().contains(ASPECTJ_GEN_METHOD)) {
statement = statement.replaceAll("\\$s", "\\ajc\\$this");
String methodName =
method.getName().substring(0, method.getName().indexOf(ASPECTJ_GEN_METHOD));
classInjector.insertMethod(method.getName(),
ctClassToString(method.getParameterTypes()))
.ifExists()
.afterACallTo(methodName, statement)
.inject()
.inject();
} else {
statement = statement.replaceAll("\\$s", "this");
String override;
if (returnSuperClass) {
//TODO refactor method
override = "{"
+ "android.view.View $$$supercall = super."
+ method.getName()
+ "($$);"
+ statement
+ "return $$$supercall;"
+ "}";
} else {
override = "{" + "super." + method.getName() + "($$);" + statement + "}";
}
int methodLines = getMethodLines(classInjector.getCtClass(), method);
log("Method lines for " + method.getName() + " is " + methodLines + "");
classInjector.insertMethod(method.getName(),
ctClassToString(method.getParameterTypes()))
.ifExistsButNotOverride()
.override(override)
.inject()
.ifExists()
.atTheEnd(statement)
.inject()
.inject();
}
}
private int getMethodLines(CtClass ctClass, CtMethod method) {
if (!ctClass.equals(method.getDeclaringClass())) {
return 0;
}
int start = method.getMethodInfo().getLineNumber(0);
int end = method.getMethodInfo().getLineNumber(Integer.MAX_VALUE);
return end - start + 1;
}
private void insertDelegateField(ClassInjector classInjector, String delegateClassName)
throws Exception {
classInjector.insertField(delegateClassName, FIELD_VIEW_DELEGATE).initializeIt().inject();
}
void log(String message) {
logger.info("[EasyMVP] -> " + message);
}
void log(String tag, String message) {
logger.info("[EasyMVP] -> [" + tag + "] -> " + message);
}
}
``` | /content/code_sandbox/easymvp-weaver/src/main/java/easymvp/weaver/ViewDelegateBinder.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 3,224 |
```java
package easymvp.boundary;
import rx.functions.Func1;
/**
* {@code DataMapper} transforms entities from the format most convenient for the use cases, to the
* format most convenient for the presentation layer.
*
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public abstract class DataMapper<T, R> implements Func1<T, R> {
}
``` | /content/code_sandbox/easymvp-rx-api/src/main/java/easymvp/boundary/DataMapper.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 84 |
```java
package easymvp.usecase;
import javax.annotation.Nullable;
import easymvp.executer.PostExecutionThread;
import easymvp.executer.UseCaseExecutor;
import rx.Observable;
/**
* Reactive version of a {@link UseCase}.
* <p>
* The presenter simply subscribes to {@link Observable} returned by the {@link #execute(Object)} method.
*
* @param <R> The response value emitted by the Observable.
* @param <Q> The request value.
* @author Saeed Masoumi (saeed@6thsolution.com)
* @see Observable
*/
public abstract class ObservableUseCase<R, Q> extends UseCase<Observable, Q> {
private final Observable.Transformer<? super R, ? extends R> schedulersTransformer;
public ObservableUseCase(final UseCaseExecutor useCaseExecutor,
final PostExecutionThread postExecutionThread) {
super(useCaseExecutor, postExecutionThread);
schedulersTransformer = new Observable.Transformer<R, R>() {
@Override
public Observable<R> call(Observable<R> rObservable) {
return rObservable.subscribeOn(useCaseExecutor.getScheduler())
.observeOn(postExecutionThread.getScheduler());
}
};
}
@Override
public Observable<R> execute(@Nullable Q param) {
return interact(param).compose(getSchedulersTransformer());
}
@Override
protected abstract Observable<R> interact(@Nullable Q param);
private Observable.Transformer<? super R, ? extends R> getSchedulersTransformer() {
return schedulersTransformer;
}
}
``` | /content/code_sandbox/easymvp-rx-api/src/main/java/easymvp/usecase/ObservableUseCase.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 325 |
```java
package easymvp.executer;
import rx.Scheduler;
/**
* When the use case execution is done in its executor thread, It's time to update UI on the Event
* Dispatch thread.
* <p>
* An implementation of this interface will change the execution context and update the UI.
*
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public interface PostExecutionThread {
Scheduler getScheduler();
}
``` | /content/code_sandbox/easymvp-rx-api/src/main/java/easymvp/executer/PostExecutionThread.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 94 |
```java
package easymvp.executer;
import rx.Scheduler;
/**
* Represents an asynchronous execution for {@link easymvp.usecase.UseCase}. It's useful to execute use cases out of
* the UI thread to prevent it from freezing.
*
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public interface UseCaseExecutor {
Scheduler getScheduler();
}
``` | /content/code_sandbox/easymvp-rx-api/src/main/java/easymvp/executer/UseCaseExecutor.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 83 |
```qmake
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/Saeed/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# path_to_url
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
``` | /content/code_sandbox/easymvp-test/proguard-rules.pro | qmake | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 141 |
```java
package com.sixthsolution.easymvp.test.usecase;
import easymvp.executer.PostExecutionThread;
import easymvp.executer.UseCaseExecutor;
import easymvp.usecase.ObservableUseCase;
import rx.Observable;
import rx.functions.Func0;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public class IsNumberOdd extends ObservableUseCase<Boolean, Integer> {
public IsNumberOdd(UseCaseExecutor useCaseExecutor,
PostExecutionThread postExecutionThread) {
super(useCaseExecutor, postExecutionThread);
}
@Override
protected Observable<Boolean> interact(final Integer number) {
return Observable.defer(new Func0<Observable<Boolean>>() {
@Override
public Observable<Boolean> call() {
return Observable.just(number % 2 != 0);
}
});
}
}
``` | /content/code_sandbox/easymvp-test/src/test/java/com/sixthsolution/easymvp/test/usecase/IsNumberOdd.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 182 |
```java
package com.sixthsolution.easymvp.test.usecase;
import org.junit.Before;
import org.junit.Test;
import easymvp.executer.PostExecutionThread;
import easymvp.executer.UseCaseExecutor;
import rx.Scheduler;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public class UseCaseTest {
private UseCaseExecutor useCaseExecutor;
private PostExecutionThread postExecutionThread;
@Before
public void init() {
useCaseExecutor = new UseCaseExecutor() {
@Override
public Scheduler getScheduler() {
return Schedulers.immediate();
}
};
postExecutionThread = new PostExecutionThread() {
@Override
public Scheduler getScheduler() {
return Schedulers.immediate();
}
};
}
@Test
public void test_use_case_execution() {
TestSubscriber<Boolean> subscriber = new TestSubscriber<>();
IsNumberOdd isNumberOdd = new IsNumberOdd(useCaseExecutor, postExecutionThread);
isNumberOdd.execute(10).subscribe(subscriber);
subscriber.assertValue(false);
subscriber.assertCompleted();
}
}
``` | /content/code_sandbox/easymvp-test/src/test/java/com/sixthsolution/easymvp/test/usecase/UseCaseTest.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 256 |
```java
package com.sixthsolution.easymvp.test;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.RelativeLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import easymvp.annotation.ActivityView;
import easymvp.annotation.Presenter;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
@ActivityView(presenter = TestPresenter.class, layout = R.layout.activity_main)
public class SimpleAppCompatActivity extends AppCompatActivity implements View1 {
@Presenter
TestPresenter testPresenter;
@BindView(R.id.base_layout)
RelativeLayout view;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
assertNotNull(view);
}
@Override
protected void onStart() {
super.onStart();
assertNotNull(testPresenter);
assertTrue(testPresenter.isOnViewAttachedCalled());
}
@Override
protected void onStop() {
super.onStop();
assertTrue(testPresenter.isOnViewDetachedCalled());
assertFalse(testPresenter.isViewAttached());
}
@Override
protected void onDestroy() {
super.onDestroy();
assertNull(testPresenter);
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/SimpleAppCompatActivity.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 257 |
```java
package com.sixthsolution.easymvp.test;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import easymvp.annotation.FragmentView;
import easymvp.annotation.Presenter;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
@FragmentView(presenter = TestPresenter.class)
public class SimpleFragment extends Fragment implements View1 {
@Presenter
TestPresenter testPresenter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.simple_fragment, container, false);
}
@Override
public void onResume() {
super.onResume();
assertNotNull(testPresenter);
assertTrue(testPresenter.isOnViewAttachedCalled());
}
@Override
public void onPause() {
super.onPause();
assertTrue(testPresenter.isOnViewDetachedCalled());
assertFalse(testPresenter.isViewAttached());
}
@Override
public void onDestroy() {
super.onDestroy();
assertNull(testPresenter);
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/SimpleFragment.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 265 |
```java
package com.sixthsolution.easymvp.test;
import android.util.Log;
import easymvp.AbstractPresenter;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public class TestPresenter extends AbstractPresenter<View1> {
private boolean isOnViewAttachedCalled = false;
private boolean isOnViewDetachedCalled = false;
private static int counter = 0;
public int count = counter++;
@Override
public void onViewAttached(View1 view) {
super.onViewAttached(view);
isOnViewAttachedCalled = true;
Log.d("TestPresenter","onViewAttached Called");
}
@Override
public void onViewDetached() {
super.onViewDetached();
isOnViewDetachedCalled = true;
Log.d("TestPresenter","onViewDetached Called");
}
@Override
public void onDestroyed() {
super.onDestroyed();
Log.d("TestPresenter","OnDestroyed Called");
}
public boolean isOnViewAttachedCalled() {
return isOnViewAttachedCalled;
}
public boolean isOnViewDetachedCalled() {
return isOnViewDetachedCalled;
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/TestPresenter.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 254 |
```java
package com.sixthsolution.easymvp.test;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import com.sixthsolution.easymvp.test.di.ActivityComponent;
import com.sixthsolution.easymvp.test.di.CustomViewComponent;
import javax.inject.Inject;
import easymvp.annotation.CustomView;
import easymvp.annotation.Presenter;
import easymvp.annotation.PresenterId;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
@CustomView(presenter = TestPresenter.class)
public class SimpleCustomViewWithDagger extends View implements View1 {
@Inject
@Presenter
TestPresenter testPresenter;
@PresenterId
int presenterId = 1_000;
public SimpleCustomViewWithDagger(Context context) {
super(context);
}
public SimpleCustomViewWithDagger(Context context,
@Nullable AttributeSet attrs) {
super(context, attrs);
}
public SimpleCustomViewWithDagger(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public SimpleCustomViewWithDagger(Context context, int counter, ActivityComponent component) {
super(context);
presenterId += counter;
component.customViewComponent().build().injectTo(this);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
assertNotNull(testPresenter);
assertTrue(testPresenter.isOnViewAttachedCalled());
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/SimpleCustomViewWithDagger.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 337 |
```java
package com.sixthsolution.easymvp.test;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public interface View1 {
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/View1.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 40 |
```java
package com.sixthsolution.easymvp.test;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import com.sixthsolution.easymvp.test.di.ActivityComponent;
import com.sixthsolution.easymvp.test.di.DaggerActivityComponent;
import java.util.HashSet;
import java.util.Set;
import butterknife.BindView;
import butterknife.ButterKnife;
import easymvp.annotation.ActivityView;
import easymvp.annotation.Presenter;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
@ActivityView(presenter = TestPresenter.class, layout = R.layout.activity_multi_views)
public class AppCompatActivityWithMultiViewsWithDagger extends AppCompatActivity implements View1 {
@Presenter
TestPresenter testPresenter;
@BindView(R.id.container)
LinearLayout container;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
ActivityComponent component =
DaggerActivityComponent.builder().build();
component.injectTo(this);
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
assertNotNull(container);
for (int i = 0; i < 10; i++) {
View view = new SimpleCustomViewWithDagger(this, i, component);
container.addView(view);
}
}
@Override
protected void onPause() {
super.onPause();
Set<Integer> ids = new HashSet<>();
for (int i = 0; i < container.getChildCount(); i++) {
SimpleCustomViewWithDagger childView =
(SimpleCustomViewWithDagger) container.getChildAt(i);
ids.add(childView.testPresenter.count);
}
assertThat(ids.size(), is(10));
Set<TestPresenter> presenters = new HashSet<>();
for (int i = 0; i < container.getChildCount(); i++) {
SimpleCustomViewWithDagger childView =
(SimpleCustomViewWithDagger) container.getChildAt(i);
presenters.add(childView.testPresenter);
}
assertThat(presenters.size(), is(10));
}
@Override
protected void onStart() {
super.onStart();
assertNotNull(testPresenter);
assertTrue(testPresenter.isOnViewAttachedCalled());
}
@Override
protected void onStop() {
super.onStop();
assertTrue(testPresenter.isOnViewDetachedCalled());
assertFalse(testPresenter.isViewAttached());
}
@Override
protected void onDestroy() {
super.onDestroy();
assertNull(testPresenter);
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/AppCompatActivityWithMultiViewsWithDagger.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 565 |
```java
package com.sixthsolution.easymvp.test;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import easymvp.annotation.ActivityView;
import easymvp.annotation.Presenter;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
@ActivityView(presenter = TestPresenter.class)
public class SimpleAppCompatActivityWithCustomView extends AppCompatActivity implements View1 {
@Presenter
TestPresenter testPresenter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SimpleCustomView(this));
}
@Override
protected void onStart() {
super.onStart();
assertNotNull(testPresenter);
assertTrue(testPresenter.isOnViewAttachedCalled());
}
@Override
protected void onStop() {
super.onStop();
assertTrue(testPresenter.isOnViewDetachedCalled());
assertFalse(testPresenter.isViewAttached());
}
@Override
protected void onDestroy() {
super.onDestroy();
assertNull(testPresenter);
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/SimpleAppCompatActivityWithCustomView.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 247 |
```java
package com.sixthsolution.easymvp.test;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import easymvp.annotation.CustomView;
import easymvp.annotation.Presenter;
import easymvp.annotation.PresenterId;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
@CustomView(presenter = TestPresenter.class)
public class SimpleCustomView extends View implements View1 {
@Presenter
TestPresenter testPresenter;
@PresenterId
int presenterId = 1_000;
public SimpleCustomView(Context context) {
super(context);
}
public SimpleCustomView(Context context,
@Nullable AttributeSet attrs) {
super(context, attrs);
}
public SimpleCustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public SimpleCustomView(Context context, int counter) {
super(context);
presenterId += counter;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
assertNotNull(testPresenter);
assertTrue(testPresenter.isOnViewAttachedCalled());
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/SimpleCustomView.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 266 |
```java
package com.sixthsolution.easymvp.test;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import easymvp.annotation.ActivityView;
import easymvp.annotation.Presenter;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
@ActivityView(presenter = TestPresenter.class, layout = R.layout.activity_main)
public class SimpleAppCompatActivityWithFragment extends AppCompatActivity implements View1 {
@Presenter
TestPresenter testPresenter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(R.id.container,new SimpleFragment()).commit();
}
@Override
protected void onStart() {
super.onStart();
assertNotNull(testPresenter);
assertTrue(testPresenter.isOnViewAttachedCalled());
}
@Override
protected void onStop() {
super.onStop();
assertTrue(testPresenter.isOnViewDetachedCalled());
assertFalse(testPresenter.isViewAttached());
}
@Override
protected void onDestroy() {
super.onDestroy();
assertNull(testPresenter);
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/SimpleAppCompatActivityWithFragment.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 261 |
```java
package com.sixthsolution.easymvp.test;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.RelativeLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import easymvp.annotation.ActivityView;
import easymvp.annotation.Presenter;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
@ActivityView(presenter = TestPresenter.class, layout = R.layout.activity_main)
public class SimpleActivity extends Activity implements View1 {
@Presenter
TestPresenter testPresenter;
@BindView(R.id.base_layout)
RelativeLayout view;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
assertNotNull(view);
}
@Override
protected void onStart() {
super.onStart();
assertNotNull(testPresenter);
assertTrue(testPresenter.isOnViewAttachedCalled());
}
@Override
protected void onStop() {
super.onStop();
assertTrue(testPresenter.isOnViewDetachedCalled());
}
@Override
protected void onDestroy() {
super.onDestroy();
// assertNull(testPresenter);
//TODO OnLoaderReset will be called after onDestroy, so Presenter#onDestroyed will not be called here.
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/SimpleActivity.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 277 |
```java
package com.sixthsolution.easymvp.test;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import java.util.HashSet;
import java.util.Set;
import butterknife.BindView;
import butterknife.ButterKnife;
import easymvp.annotation.ActivityView;
import easymvp.annotation.Presenter;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
@ActivityView(presenter = TestPresenter.class, layout = R.layout.activity_multi_views)
public class AppCompatActivityWithMultiViews extends AppCompatActivity implements View1 {
@Presenter
TestPresenter testPresenter;
@BindView(R.id.container)
LinearLayout container;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
assertNotNull(container);
for (int i = 0; i < 10; i++) {
View view = new SimpleCustomView(this, i);
container.addView(view);
}
}
@Override
protected void onPause() {
super.onPause();
Set<Integer> ids = new HashSet<>();
for (int i = 0; i < container.getChildCount(); i++) {
SimpleCustomView childView = (SimpleCustomView) container.getChildAt(i);
ids.add(childView.testPresenter.count);
}
assertThat(ids.size(), is(10));
}
@Override
protected void onStart() {
super.onStart();
assertNotNull(testPresenter);
assertTrue(testPresenter.isOnViewAttachedCalled());
}
@Override
protected void onStop() {
super.onStop();
assertTrue(testPresenter.isOnViewDetachedCalled());
assertFalse(testPresenter.isViewAttached());
}
@Override
protected void onDestroy() {
super.onDestroy();
assertNull(testPresenter);
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/AppCompatActivityWithMultiViews.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 435 |
```java
package com.sixthsolution.easymvp.test.di;
import com.sixthsolution.easymvp.test.AppCompatActivityWithMultiViewsWithDagger;
import javax.inject.Singleton;
import dagger.Component;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
@Singleton
@Component
public interface ActivityComponent {
CustomViewComponent.Builder customViewComponent();
void injectTo(AppCompatActivityWithMultiViewsWithDagger activity);
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/di/ActivityComponent.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 97 |
```java
package com.sixthsolution.easymvp.test.di;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomScope {
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/di/CustomScope.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 72 |
```java
package com.sixthsolution.easymvp.test.di;
import com.sixthsolution.easymvp.test.TestPresenter;
import dagger.Module;
import dagger.Provides;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
@Module
public class CustomModule {
@CustomScope
@Provides
public TestPresenter providePresenter() {
return new TestPresenter();
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/di/CustomModule.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 91 |
```java
package com.sixthsolution.easymvp.test.di;
import com.sixthsolution.easymvp.test.SimpleCustomViewWithDagger;
import dagger.Subcomponent;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
@CustomScope
@Subcomponent(modules = CustomModule.class)
public interface CustomViewComponent {
void injectTo(SimpleCustomViewWithDagger simpleCustomViewWithDagger);
@Subcomponent.Builder
interface Builder {
CustomViewComponent build();
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/di/CustomViewComponent.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 115 |
```java
package com.sixthsolution.easymvp.test.conductor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.bluelinelabs.conductor.Conductor;
import com.bluelinelabs.conductor.Router;
import com.bluelinelabs.conductor.RouterTransaction;
import com.sixthsolution.easymvp.test.R;
import butterknife.BindView;
import butterknife.ButterKnife;
import static junit.framework.Assert.assertNotNull;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
public class ConductorActivity extends AppCompatActivity {
@BindView(R.id.base_layout)
RelativeLayout view;
private Router router;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
assertNotNull(view);
router = Conductor.attachRouter(this, (ViewGroup) findViewById(R.id.container),
savedInstanceState);
if (!router.hasRootController()) {
router.setRoot(RouterTransaction.with(new TestController()));
}
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/conductor/ConductorActivity.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 233 |
```java
package com.sixthsolution.easymvp.test.conductor;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bluelinelabs.conductor.Controller;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
public class BaseController extends Controller{
@NonNull
@Override
protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
return null;
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/conductor/BaseController.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 103 |
```java
package com.sixthsolution.easymvp.test.conductor;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.sixthsolution.easymvp.test.R;
import com.sixthsolution.easymvp.test.TestPresenter;
import com.sixthsolution.easymvp.test.View1;
import easymvp.annotation.Presenter;
import easymvp.annotation.conductor.ConductorController;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertNull;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
@ConductorController(presenter = TestPresenter.class)
public class TestController extends BaseController implements View1 {
@Presenter
TestPresenter testPresenter;
@NonNull
@Override
protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
return inflater.inflate(R.layout.simple_fragment, container, false);
}
@Override
protected void onAttach(@NonNull View view) {
super.onAttach(view);
assertNotNull(testPresenter);
assertTrue(testPresenter.isOnViewAttachedCalled());
}
@Override
protected void onDetach(@NonNull View view) {
super.onDetach(view);
assertTrue(testPresenter.isOnViewDetachedCalled());
assertFalse(testPresenter.isViewAttached());
}
@Override
protected void onDestroy() {
super.onDestroy();
assertNull(testPresenter);
}
}
``` | /content/code_sandbox/easymvp-test/src/main/java/com/sixthsolution/easymvp/test/conductor/TestController.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 314 |
```java
package com.sixthsolution.easymvp.test;
import android.support.test.filters.MediumTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
@MediumTest
@RunWith(AndroidJUnit4.class)
public class AppCompatActivityViewTest {
@Rule
public ActivityTestRule<SimpleAppCompatActivity> activityRule = new ActivityTestRule<>(
SimpleAppCompatActivity.class);
@Test
public void layout_already_inflated_with_ActivityView_annotation() {
onView(withId(R.id.base_layout)).check(matches(isDisplayed()));
}
}
``` | /content/code_sandbox/easymvp-test/src/androidTest/java/com/sixthsolution/easymvp/test/AppCompatActivityViewTest.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 204 |
```java
package com.sixthsolution.easymvp.test;
import android.support.test.filters.MediumTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
@MediumTest
@RunWith(AndroidJUnit4.class)
public class MultipleChildViewsTest {
@Rule
public ActivityTestRule<AppCompatActivityWithMultiViews> activityRule = new ActivityTestRule<>(
AppCompatActivityWithMultiViews.class);
@Test
public void layout_already_inflated_with_ActivityView_annotation() {
onView(withId(R.id.container)).check(matches(isDisplayed()));
}
}
``` | /content/code_sandbox/easymvp-test/src/androidTest/java/com/sixthsolution/easymvp/test/MultipleChildViewsTest.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 206 |
```java
package com.sixthsolution.easymvp.test;
import android.support.test.filters.MediumTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
@MediumTest
@RunWith(AndroidJUnit4.class)
public class ActivityViewTest {
@Rule
public ActivityTestRule<SimpleActivity> activityRule = new ActivityTestRule<>(
SimpleActivity.class);
@Test
public void layout_already_inflated_with_ActivityView_annotation() {
onView(withId(R.id.base_layout)).check(matches(isDisplayed()));
}
}
``` | /content/code_sandbox/easymvp-test/src/androidTest/java/com/sixthsolution/easymvp/test/ActivityViewTest.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 202 |
```java
package com.sixthsolution.easymvp.test;
import android.support.test.rule.ActivityTestRule;
import android.view.View;
import org.junit.Rule;
import org.junit.Test;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
public class CustomViewTest {
@Rule
public ActivityTestRule<SimpleAppCompatActivityWithCustomView> activityRule = new ActivityTestRule<>(
SimpleAppCompatActivityWithCustomView.class);
@Test
public void custom_view_already_attached() {
View contentView = activityRule.getActivity().findViewById(android.R.id.content);
}
}
``` | /content/code_sandbox/easymvp-test/src/androidTest/java/com/sixthsolution/easymvp/test/CustomViewTest.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 129 |
```java
package com.sixthsolution.easymvp.test;
import android.support.test.filters.MediumTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
/**
* @author Saeed Masoumi (saeed@6thsolution.com)
*/
@MediumTest
@RunWith(AndroidJUnit4.class)
public class FragmentViewTest {
@Rule
public ActivityTestRule<SimpleAppCompatActivityWithFragment> activityRule = new ActivityTestRule<>(
SimpleAppCompatActivityWithFragment.class);
@Test
public void layout_already_inflated_with_ActivityView_annotation() {
onView(withId(R.id.base_layout)).check(matches(isDisplayed()));
}
@Test
public void fragment_already_attached(){
onView(withId(R.id.base_fragment)).check(matches(isDisplayed()));
}
}
``` | /content/code_sandbox/easymvp-test/src/androidTest/java/com/sixthsolution/easymvp/test/FragmentViewTest.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 234 |
```java
package com.sixthsolution.easymvp.test;
import android.support.test.filters.MediumTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
@MediumTest
@RunWith(AndroidJUnit4.class)
public class MultipleChildViewsTestWithDagger {
@Rule
public ActivityTestRule<AppCompatActivityWithMultiViewsWithDagger> activityRule = new ActivityTestRule<>(
AppCompatActivityWithMultiViewsWithDagger.class);
@Test
public void layout_already_inflated_with_ActivityView_annotation() {
onView(withId(R.id.container)).check(matches(isDisplayed()));
}
}
``` | /content/code_sandbox/easymvp-test/src/androidTest/java/com/sixthsolution/easymvp/test/MultipleChildViewsTestWithDagger.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 215 |
```java
package com.sixthsolution.easymvp.test.conductor;
import android.support.test.filters.MediumTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.sixthsolution.easymvp.test.R;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
/**
* @author Saeed Masoumi (s-masoumi@live.com)
*/
@MediumTest
@RunWith(AndroidJUnit4.class)
public class ConductorTest {
@Rule
public ActivityTestRule<ConductorActivity> activityRule = new ActivityTestRule<>(
ConductorActivity.class);
@Test
public void layout_already_inflated_with_ActivityView_annotation() {
onView(withId(R.id.base_fragment)).check(matches(isDisplayed()));
}
}
``` | /content/code_sandbox/easymvp-test/src/androidTest/java/com/sixthsolution/easymvp/test/conductor/ConductorTest.java | java | 2016-04-18T07:36:33 | 2024-07-24T13:57:59 | EasyMVP | 6thsolution/EasyMVP | 1,296 | 219 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.